-
Notifications
You must be signed in to change notification settings - Fork 728
/
Copy pathcontainers.py
2699 lines (2276 loc) · 95.2 KB
/
containers.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
"""
Container for the layout.
(Containers can contain other containers or user interface controls.)
"""
from abc import ABCMeta, abstractmethod
from enum import Enum
from functools import partial
from typing import (
TYPE_CHECKING,
Callable,
Dict,
List,
Optional,
Sequence,
Tuple,
Union,
cast,
)
from prompt_toolkit.application.current import get_app
from prompt_toolkit.cache import SimpleCache
from prompt_toolkit.data_structures import Point
from prompt_toolkit.filters import (
FilterOrBool,
emacs_insert_mode,
to_filter,
vi_insert_mode,
)
from prompt_toolkit.formatted_text import (
AnyFormattedText,
StyleAndTextTuples,
to_formatted_text,
)
from prompt_toolkit.formatted_text.utils import (
fragment_list_to_text,
fragment_list_width,
)
from prompt_toolkit.key_binding import KeyBindingsBase
from prompt_toolkit.mouse_events import MouseEvent, MouseEventType
from prompt_toolkit.utils import get_cwidth, take_using_weights, to_int, to_str
from .controls import (
DummyControl,
FormattedTextControl,
GetLinePrefixCallable,
UIContent,
UIControl,
)
from .dimension import (
AnyDimension,
Dimension,
max_layout_dimensions,
sum_layout_dimensions,
to_dimension,
)
from .margins import Margin
from .mouse_handlers import MouseHandlers
from .screen import _CHAR_CACHE, Screen, WritePosition
from .utils import explode_text_fragments
if TYPE_CHECKING:
from typing_extensions import Protocol
NotImplementedOrNone = object
__all__ = [
"Container",
"HorizontalAlign",
"VerticalAlign",
"HSplit",
"VSplit",
"FloatContainer",
"Float",
"WindowAlign",
"Window",
"WindowRenderInfo",
"ConditionalContainer",
"ScrollOffsets",
"ColorColumn",
"to_container",
"to_window",
"is_container",
"DynamicContainer",
]
class Container(metaclass=ABCMeta):
"""
Base class for user interface layout.
"""
@abstractmethod
def reset(self) -> None:
"""
Reset the state of this container and all the children.
(E.g. reset scroll offsets, etc...)
"""
@abstractmethod
def preferred_width(self, max_available_width: int) -> Dimension:
"""
Return a :class:`~prompt_toolkit.layout.Dimension` that represents the
desired width for this container.
"""
@abstractmethod
def preferred_height(self, width: int, max_available_height: int) -> Dimension:
"""
Return a :class:`~prompt_toolkit.layout.Dimension` that represents the
desired height for this container.
"""
@abstractmethod
def write_to_screen(
self,
screen: Screen,
mouse_handlers: MouseHandlers,
write_position: WritePosition,
parent_style: str,
erase_bg: bool,
z_index: Optional[int],
) -> None:
"""
Write the actual content to the screen.
:param screen: :class:`~prompt_toolkit.layout.screen.Screen`
:param mouse_handlers: :class:`~prompt_toolkit.layout.mouse_handlers.MouseHandlers`.
:param parent_style: Style string to pass to the :class:`.Window`
object. This will be applied to all content of the windows.
:class:`.VSplit` and :class:`.HSplit` can use it to pass their
style down to the windows that they contain.
:param z_index: Used for propagating z_index from parent to child.
"""
def is_modal(self) -> bool:
"""
When this container is modal, key bindings from parent containers are
not taken into account if a user control in this container is focused.
"""
return False
def get_key_bindings(self) -> Optional[KeyBindingsBase]:
"""
Returns a :class:`.KeyBindings` object. These bindings become active when any
user control in this container has the focus, except if any containers
between this container and the focused user control is modal.
"""
return None
@abstractmethod
def get_children(self) -> List["Container"]:
"""
Return the list of child :class:`.Container` objects.
"""
return []
if TYPE_CHECKING:
class MagicContainer(Protocol):
"""
Any object that implements ``__pt_container__`` represents a container.
"""
def __pt_container__(self) -> "AnyContainer":
...
AnyContainer = Union[Container, "MagicContainer"]
def _window_too_small() -> "Window":
" Create a `Window` that displays the 'Window too small' text. "
return Window(
FormattedTextControl(text=[("class:window-too-small", " Window too small... ")])
)
class VerticalAlign(Enum):
" Alignment for `HSplit`. "
TOP = "TOP"
CENTER = "CENTER"
BOTTOM = "BOTTOM"
JUSTIFY = "JUSTIFY"
class HorizontalAlign(Enum):
" Alignment for `VSplit`. "
LEFT = "LEFT"
CENTER = "CENTER"
RIGHT = "RIGHT"
JUSTIFY = "JUSTIFY"
class _Split(Container):
"""
The common parts of `VSplit` and `HSplit`.
"""
def __init__(
self,
children: Sequence[AnyContainer],
window_too_small: Optional[Container] = None,
padding: AnyDimension = Dimension.exact(0),
padding_char: Optional[str] = None,
padding_style: str = "",
width: AnyDimension = None,
height: AnyDimension = None,
z_index: Optional[int] = None,
modal: bool = False,
key_bindings: Optional[KeyBindingsBase] = None,
style: Union[str, Callable[[], str]] = "",
) -> None:
self.children = [to_container(c) for c in children]
self.window_too_small = window_too_small or _window_too_small()
self.padding = padding
self.padding_char = padding_char
self.padding_style = padding_style
self.width = width
self.height = height
self.z_index = z_index
self.modal = modal
self.key_bindings = key_bindings
self.style = style
def is_modal(self) -> bool:
return self.modal
def get_key_bindings(self) -> Optional[KeyBindingsBase]:
return self.key_bindings
def get_children(self) -> List[Container]:
return self.children
class HSplit(_Split):
"""
Several layouts, one stacked above/under the other. ::
+--------------------+
| |
+--------------------+
| |
+--------------------+
By default, this doesn't display a horizontal line between the children,
but if this is something you need, then create a HSplit as follows::
HSplit(children=[ ... ], padding_char='-',
padding=1, padding_style='#ffff00')
:param children: List of child :class:`.Container` objects.
:param window_too_small: A :class:`.Container` object that is displayed if
there is not enough space for all the children. By default, this is a
"Window too small" message.
:param align: `VerticalAlign` value.
:param width: When given, use this width instead of looking at the children.
:param height: When given, use this height instead of looking at the children.
:param z_index: (int or None) When specified, this can be used to bring
element in front of floating elements. `None` means: inherit from parent.
:param style: A style string.
:param modal: ``True`` or ``False``.
:param key_bindings: ``None`` or a :class:`.KeyBindings` object.
:param padding: (`Dimension` or int), size to be used for the padding.
:param padding_char: Character to be used for filling in the padding.
:param padding_style: Style to applied to the padding.
"""
def __init__(
self,
children: Sequence[AnyContainer],
window_too_small: Optional[Container] = None,
align: VerticalAlign = VerticalAlign.JUSTIFY,
padding: AnyDimension = 0,
padding_char: Optional[str] = None,
padding_style: str = "",
width: AnyDimension = None,
height: AnyDimension = None,
z_index: Optional[int] = None,
modal: bool = False,
key_bindings: Optional[KeyBindingsBase] = None,
style: Union[str, Callable[[], str]] = "",
) -> None:
super().__init__(
children=children,
window_too_small=window_too_small,
padding=padding,
padding_char=padding_char,
padding_style=padding_style,
width=width,
height=height,
z_index=z_index,
modal=modal,
key_bindings=key_bindings,
style=style,
)
self.align = align
self._children_cache: SimpleCache[
Tuple[Container, ...], List[Container]
] = SimpleCache(maxsize=1)
self._remaining_space_window = Window() # Dummy window.
def preferred_width(self, max_available_width: int) -> Dimension:
if self.width is not None:
return to_dimension(self.width)
if self.children:
dimensions = [c.preferred_width(max_available_width) for c in self.children]
return max_layout_dimensions(dimensions)
else:
return Dimension()
def preferred_height(self, width: int, max_available_height: int) -> Dimension:
if self.height is not None:
return to_dimension(self.height)
dimensions = [
c.preferred_height(width, max_available_height) for c in self._all_children
]
return sum_layout_dimensions(dimensions)
def reset(self) -> None:
for c in self.children:
c.reset()
@property
def _all_children(self) -> List[Container]:
"""
List of child objects, including padding.
"""
def get() -> List[Container]:
result: List[Container] = []
# Padding Top.
if self.align in (VerticalAlign.CENTER, VerticalAlign.BOTTOM):
result.append(Window(width=Dimension(preferred=0)))
# The children with padding.
for child in self.children:
result.append(child)
result.append(
Window(
height=self.padding,
char=self.padding_char,
style=self.padding_style,
)
)
result.pop()
# Padding right.
if self.align in (VerticalAlign.CENTER, VerticalAlign.TOP):
result.append(Window(width=Dimension(preferred=0)))
return result
return self._children_cache.get(tuple(self.children), get)
def write_to_screen(
self,
screen: Screen,
mouse_handlers: MouseHandlers,
write_position: WritePosition,
parent_style: str,
erase_bg: bool,
z_index: Optional[int],
) -> None:
"""
Render the prompt to a `Screen` instance.
:param screen: The :class:`~prompt_toolkit.layout.screen.Screen` class
to which the output has to be written.
"""
sizes = self._divide_heights(write_position)
style = parent_style + " " + to_str(self.style)
z_index = z_index if self.z_index is None else self.z_index
if sizes is None:
self.window_too_small.write_to_screen(
screen, mouse_handlers, write_position, style, erase_bg, z_index
)
else:
#
ypos = write_position.ypos
xpos = write_position.xpos
width = write_position.width
# Draw child panes.
for s, c in zip(sizes, self._all_children):
c.write_to_screen(
screen,
mouse_handlers,
WritePosition(xpos, ypos, width, s),
style,
erase_bg,
z_index,
)
ypos += s
# Fill in the remaining space. This happens when a child control
# refuses to take more space and we don't have any padding. Adding a
# dummy child control for this (in `self._all_children`) is not
# desired, because in some situations, it would take more space, even
# when it's not required. This is required to apply the styling.
remaining_height = write_position.ypos + write_position.height - ypos
if remaining_height > 0:
self._remaining_space_window.write_to_screen(
screen,
mouse_handlers,
WritePosition(xpos, ypos, width, remaining_height),
style,
erase_bg,
z_index,
)
def _divide_heights(self, write_position: WritePosition) -> Optional[List[int]]:
"""
Return the heights for all rows.
Or None when there is not enough space.
"""
if not self.children:
return []
width = write_position.width
height = write_position.height
# Calculate heights.
dimensions = [c.preferred_height(width, height) for c in self._all_children]
# Sum dimensions
sum_dimensions = sum_layout_dimensions(dimensions)
# If there is not enough space for both.
# Don't do anything.
if sum_dimensions.min > height:
return None
# Find optimal sizes. (Start with minimal size, increase until we cover
# the whole height.)
sizes = [d.min for d in dimensions]
child_generator = take_using_weights(
items=list(range(len(dimensions))), weights=[d.weight for d in dimensions]
)
i = next(child_generator)
# Increase until we meet at least the 'preferred' size.
preferred_stop = min(height, sum_dimensions.preferred)
preferred_dimensions = [d.preferred for d in dimensions]
while sum(sizes) < preferred_stop:
if sizes[i] < preferred_dimensions[i]:
sizes[i] += 1
i = next(child_generator)
# Increase until we use all the available space. (or until "max")
if not get_app().is_done:
max_stop = min(height, sum_dimensions.max)
max_dimensions = [d.max for d in dimensions]
while sum(sizes) < max_stop:
if sizes[i] < max_dimensions[i]:
sizes[i] += 1
i = next(child_generator)
return sizes
class VSplit(_Split):
"""
Several layouts, one stacked left/right of the other. ::
+---------+----------+
| | |
| | |
+---------+----------+
By default, this doesn't display a vertical line between the children, but
if this is something you need, then create a HSplit as follows::
VSplit(children=[ ... ], padding_char='|',
padding=1, padding_style='#ffff00')
:param children: List of child :class:`.Container` objects.
:param window_too_small: A :class:`.Container` object that is displayed if
there is not enough space for all the children. By default, this is a
"Window too small" message.
:param align: `HorizontalAlign` value.
:param width: When given, use this width instead of looking at the children.
:param height: When given, use this height instead of looking at the children.
:param z_index: (int or None) When specified, this can be used to bring
element in front of floating elements. `None` means: inherit from parent.
:param style: A style string.
:param modal: ``True`` or ``False``.
:param key_bindings: ``None`` or a :class:`.KeyBindings` object.
:param padding: (`Dimension` or int), size to be used for the padding.
:param padding_char: Character to be used for filling in the padding.
:param padding_style: Style to applied to the padding.
"""
def __init__(
self,
children: Sequence[AnyContainer],
window_too_small: Optional[Container] = None,
align: HorizontalAlign = HorizontalAlign.JUSTIFY,
padding: AnyDimension = 0,
padding_char: Optional[str] = None,
padding_style: str = "",
width: AnyDimension = None,
height: AnyDimension = None,
z_index: Optional[int] = None,
modal: bool = False,
key_bindings: Optional[KeyBindingsBase] = None,
style: Union[str, Callable[[], str]] = "",
) -> None:
super().__init__(
children=children,
window_too_small=window_too_small,
padding=padding,
padding_char=padding_char,
padding_style=padding_style,
width=width,
height=height,
z_index=z_index,
modal=modal,
key_bindings=key_bindings,
style=style,
)
self.align = align
self._children_cache: SimpleCache[
Tuple[Container, ...], List[Container]
] = SimpleCache(maxsize=1)
self._remaining_space_window = Window() # Dummy window.
def preferred_width(self, max_available_width: int) -> Dimension:
if self.width is not None:
return to_dimension(self.width)
dimensions = [
c.preferred_width(max_available_width) for c in self._all_children
]
return sum_layout_dimensions(dimensions)
def preferred_height(self, width: int, max_available_height: int) -> Dimension:
if self.height is not None:
return to_dimension(self.height)
# At the point where we want to calculate the heights, the widths have
# already been decided. So we can trust `width` to be the actual
# `width` that's going to be used for the rendering. So,
# `divide_widths` is supposed to use all of the available width.
# Using only the `preferred` width caused a bug where the reported
# height was more than required. (we had a `BufferControl` which did
# wrap lines because of the smaller width returned by `_divide_widths`.
sizes = self._divide_widths(width)
children = self._all_children
if sizes is None:
return Dimension()
else:
dimensions = [
c.preferred_height(s, max_available_height)
for s, c in zip(sizes, children)
]
return max_layout_dimensions(dimensions)
def reset(self) -> None:
for c in self.children:
c.reset()
@property
def _all_children(self) -> List[Container]:
"""
List of child objects, including padding.
"""
def get() -> List[Container]:
result: List[Container] = []
# Padding left.
if self.align in (HorizontalAlign.CENTER, HorizontalAlign.RIGHT):
result.append(Window(width=Dimension(preferred=0)))
# The children with padding.
for child in self.children:
result.append(child)
result.append(
Window(
width=self.padding,
char=self.padding_char,
style=self.padding_style,
)
)
result.pop()
# Padding right.
if self.align in (HorizontalAlign.CENTER, HorizontalAlign.LEFT):
result.append(Window(width=Dimension(preferred=0)))
return result
return self._children_cache.get(tuple(self.children), get)
def _divide_widths(self, width: int) -> Optional[List[int]]:
"""
Return the widths for all columns.
Or None when there is not enough space.
"""
children = self._all_children
if not children:
return []
# Calculate widths.
dimensions = [c.preferred_width(width) for c in children]
preferred_dimensions = [d.preferred for d in dimensions]
# Sum dimensions
sum_dimensions = sum_layout_dimensions(dimensions)
# If there is not enough space for both.
# Don't do anything.
if sum_dimensions.min > width:
return None
# Find optimal sizes. (Start with minimal size, increase until we cover
# the whole width.)
sizes = [d.min for d in dimensions]
child_generator = take_using_weights(
items=list(range(len(dimensions))), weights=[d.weight for d in dimensions]
)
i = next(child_generator)
# Increase until we meet at least the 'preferred' size.
preferred_stop = min(width, sum_dimensions.preferred)
while sum(sizes) < preferred_stop:
if sizes[i] < preferred_dimensions[i]:
sizes[i] += 1
i = next(child_generator)
# Increase until we use all the available space.
max_dimensions = [d.max for d in dimensions]
max_stop = min(width, sum_dimensions.max)
while sum(sizes) < max_stop:
if sizes[i] < max_dimensions[i]:
sizes[i] += 1
i = next(child_generator)
return sizes
def write_to_screen(
self,
screen: Screen,
mouse_handlers: MouseHandlers,
write_position: WritePosition,
parent_style: str,
erase_bg: bool,
z_index: Optional[int],
) -> None:
"""
Render the prompt to a `Screen` instance.
:param screen: The :class:`~prompt_toolkit.layout.screen.Screen` class
to which the output has to be written.
"""
if not self.children:
return
children = self._all_children
sizes = self._divide_widths(write_position.width)
style = parent_style + " " + to_str(self.style)
z_index = z_index if self.z_index is None else self.z_index
# If there is not enough space.
if sizes is None:
self.window_too_small.write_to_screen(
screen, mouse_handlers, write_position, style, erase_bg, z_index
)
return
# Calculate heights, take the largest possible, but not larger than
# write_position.height.
heights = [
child.preferred_height(width, write_position.height).preferred
for width, child in zip(sizes, children)
]
height = max(write_position.height, min(write_position.height, max(heights)))
#
ypos = write_position.ypos
xpos = write_position.xpos
# Draw all child panes.
for s, c in zip(sizes, children):
c.write_to_screen(
screen,
mouse_handlers,
WritePosition(xpos, ypos, s, height),
style,
erase_bg,
z_index,
)
xpos += s
# Fill in the remaining space. This happens when a child control
# refuses to take more space and we don't have any padding. Adding a
# dummy child control for this (in `self._all_children`) is not
# desired, because in some situations, it would take more space, even
# when it's not required. This is required to apply the styling.
remaining_width = write_position.xpos + write_position.width - xpos
if remaining_width > 0:
self._remaining_space_window.write_to_screen(
screen,
mouse_handlers,
WritePosition(xpos, ypos, remaining_width, height),
style,
erase_bg,
z_index,
)
class FloatContainer(Container):
"""
Container which can contain another container for the background, as well
as a list of floating containers on top of it.
Example Usage::
FloatContainer(content=Window(...),
floats=[
Float(xcursor=True,
ycursor=True,
layout=CompletionMenu(...))
])
:param z_index: (int or None) When specified, this can be used to bring
element in front of floating elements. `None` means: inherit from parent.
This is the z_index for the whole `Float` container as a whole.
"""
def __init__(
self,
content: AnyContainer,
floats: List["Float"],
modal: bool = False,
key_bindings: Optional[KeyBindingsBase] = None,
style: Union[str, Callable[[], str]] = "",
z_index: Optional[int] = None,
) -> None:
self.content = to_container(content)
self.floats = floats
self.modal = modal
self.key_bindings = key_bindings
self.style = style
self.z_index = z_index
def reset(self) -> None:
self.content.reset()
for f in self.floats:
f.content.reset()
def preferred_width(self, max_available_width: int) -> Dimension:
return self.content.preferred_width(max_available_width)
def preferred_height(self, width: int, max_available_height: int) -> Dimension:
"""
Return the preferred height of the float container.
(We don't care about the height of the floats, they should always fit
into the dimensions provided by the container.)
"""
return self.content.preferred_height(width, max_available_height)
def write_to_screen(
self,
screen: Screen,
mouse_handlers: MouseHandlers,
write_position: WritePosition,
parent_style: str,
erase_bg: bool,
z_index: Optional[int],
) -> None:
style = parent_style + " " + to_str(self.style)
z_index = z_index if self.z_index is None else self.z_index
self.content.write_to_screen(
screen, mouse_handlers, write_position, style, erase_bg, z_index
)
for number, fl in enumerate(self.floats):
# z_index of a Float is computed by summing the z_index of the
# container and the `Float`.
new_z_index = (z_index or 0) + fl.z_index
style = parent_style + " " + to_str(self.style)
# If the float that we have here, is positioned relative to the
# cursor position, but the Window that specifies the cursor
# position is not drawn yet, because it's a Float itself, we have
# to postpone this calculation. (This is a work-around, but good
# enough for now.)
postpone = fl.xcursor is not None or fl.ycursor is not None
if postpone:
new_z_index = (
number + 10 ** 8
) # Draw as late as possible, but keep the order.
screen.draw_with_z_index(
z_index=new_z_index,
draw_func=partial(
self._draw_float,
fl,
screen,
mouse_handlers,
write_position,
style,
erase_bg,
new_z_index,
),
)
else:
self._draw_float(
fl,
screen,
mouse_handlers,
write_position,
style,
erase_bg,
new_z_index,
)
def _draw_float(
self,
fl: "Float",
screen: Screen,
mouse_handlers: MouseHandlers,
write_position: WritePosition,
style: str,
erase_bg: bool,
z_index: Optional[int],
) -> None:
" Draw a single Float. "
# When a menu_position was given, use this instead of the cursor
# position. (These cursor positions are absolute, translate again
# relative to the write_position.)
# Note: This should be inside the for-loop, because one float could
# set the cursor position to be used for the next one.
cpos = screen.get_menu_position(
fl.attach_to_window or get_app().layout.current_window
)
cursor_position = Point(
x=cpos.x - write_position.xpos, y=cpos.y - write_position.ypos
)
fl_width = fl.get_width()
fl_height = fl.get_height()
width: int
height: int
xpos: int
ypos: int
# Left & width given.
if fl.left is not None and fl_width is not None:
xpos = fl.left
width = fl_width
# Left & right given -> calculate width.
elif fl.left is not None and fl.right is not None:
xpos = fl.left
width = write_position.width - fl.left - fl.right
# Width & right given -> calculate left.
elif fl_width is not None and fl.right is not None:
xpos = write_position.width - fl.right - fl_width
width = fl_width
# Near x position of cursor.
elif fl.xcursor:
if fl_width is None:
width = fl.content.preferred_width(write_position.width).preferred
width = min(write_position.width, width)
else:
width = fl_width
xpos = cursor_position.x
if xpos + width > write_position.width:
xpos = max(0, write_position.width - width)
# Only width given -> center horizontally.
elif fl_width:
xpos = int((write_position.width - fl_width) / 2)
width = fl_width
# Otherwise, take preferred width from float content.
else:
width = fl.content.preferred_width(write_position.width).preferred
if fl.left is not None:
xpos = fl.left
elif fl.right is not None:
xpos = max(0, write_position.width - width - fl.right)
else: # Center horizontally.
xpos = max(0, int((write_position.width - width) / 2))
# Trim.
width = min(width, write_position.width - xpos)
# Top & height given.
if fl.top is not None and fl_height is not None:
ypos = fl.top
height = fl_height
# Top & bottom given -> calculate height.
elif fl.top is not None and fl.bottom is not None:
ypos = fl.top
height = write_position.height - fl.top - fl.bottom
# Height & bottom given -> calculate top.
elif fl_height is not None and fl.bottom is not None:
ypos = write_position.height - fl_height - fl.bottom
height = fl_height
# Near cursor.
elif fl.ycursor:
ypos = cursor_position.y + (0 if fl.allow_cover_cursor else 1)
if fl_height is None:
height = fl.content.preferred_height(
width, write_position.height
).preferred
else:
height = fl_height
# Reduce height if not enough space. (We can use the height
# when the content requires it.)
if height > write_position.height - ypos:
if write_position.height - ypos + 1 >= ypos:
# When the space below the cursor is more than
# the space above, just reduce the height.
height = write_position.height - ypos
else:
# Otherwise, fit the float above the cursor.
height = min(height, cursor_position.y)
ypos = cursor_position.y - height
# Only height given -> center vertically.
elif fl_height:
ypos = int((write_position.height - fl_height) / 2)
height = fl_height
# Otherwise, take preferred height from content.
else:
height = fl.content.preferred_height(width, write_position.height).preferred
if fl.top is not None:
ypos = fl.top
elif fl.bottom is not None:
ypos = max(0, write_position.height - height - fl.bottom)
else: # Center vertically.
ypos = max(0, int((write_position.height - height) / 2))
# Trim.
height = min(height, write_position.height - ypos)
# Write float.
# (xpos and ypos can be negative: a float can be partially visible.)
if height > 0 and width > 0:
wp = WritePosition(
xpos=xpos + write_position.xpos,
ypos=ypos + write_position.ypos,
width=width,
height=height,
)
if not fl.hide_when_covering_content or self._area_is_empty(screen, wp):
fl.content.write_to_screen(
screen,
mouse_handlers,
wp,
style,
erase_bg=not fl.transparent(),
z_index=z_index,
)
def _area_is_empty(self, screen: Screen, write_position: WritePosition) -> bool:
"""
Return True when the area below the write position is still empty.
(For floats that should not hide content underneath.)
"""
wp = write_position