# MIT License
#
# Copyright (c) 2021 Eugenio Parodi <ceccopierangiolieugenio AT googlemail DOT com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
'''
**Layout** [:ref:`Tutorial <Layout-Tutorial_Intro>`]
'''
from __future__ import annotations
__all__ = ['TTkLayoutItem', 'TTkLayout', 'TTkWidgetItem']
from typing import TYPE_CHECKING, Generator, List, Optional
from TermTk.TTkCore.constant import TTkK
from .layoutitem import TTkLayoutItem, TTkWidgetItem
if TYPE_CHECKING:
from TermTk.TTkWidgets.widget import TTkWidget
[docs]
class TTkLayout(TTkLayoutItem):
'''
| The :py:class:`TTkLayout` class is the base class of geometry managers. <br/>
| It allows free placement of the widgets in the layout area. <br/>
| Used mainly to have free range moving :py:class:`TTkWindow` because the widgets are not automatically rearranged after a layout event
::
╔════════════════════════════╗
║ pos(4,2) ║
║ ┌───────┐ pos(16,4) ║
║ │Widget1│ ┌─────────┐ ║
║ │ │ │ Widget2 │ ║
║ │ │ └─────────┘ ║
║ │ │ ║
║ └───────┘ ║
║ ║
╚════════════════════════════╝
'''
__slots__ = ('_items', '_zSortedItems')
_items:List[TTkLayoutItem]
_zSortedItems:List[TTkLayoutItem]
def __init__(self, **kwargs) -> None:
super().__init__(**kwargs)
self._items = []
self._zSortedItems = []
[docs]
def children(self):
'''Return the list of direct child layout items.'''
return self._items
[docs]
def count(self):
'''Return the number of direct child layout items.'''
return len(self._items)
[docs]
def itemAt(self, index):
'''Return the item at ``index`` or ``None`` when out of range.
:param index: child index
:type index: int
:return: the layout item at ``index`` if available
:rtype: :py:class:`TTkLayoutItem` or None
'''
if index < len(self._items):
return self._items[index]
return None
[docs]
def setParent(self, parent):
'''Set the parent layout item and propagate parent widget ownership.
:param parent: parent layout item or widget-like owner
:type parent: object
'''
if parent is None:
self._parent = parent
elif isinstance(parent, TTkLayoutItem):
self._parent = parent
else:
self._parent = parent.widgetItem()
for item in self._items:
item.setParent(self)
if isinstance(item, TTkWidgetItem):
item.widget().setParent(self.parentWidget())
def _zSortItems(self):
'''Sort child items by z-order and cache the sorted list.'''
self._zSortedItems = sorted(self._items, key=lambda item: item._z)
@property
def zSortedItems(self):
'''Return child items sorted by z-order.'''
return self._zSortedItems
[docs]
def replaceItem(self, item, index):
'''Replace the item at ``index`` with ``item``.
:param item: replacement item
:type item: :py:class:`TTkLayoutItem`
:param index: target index to replace
:type index: int
:raises ValueError: if ``index`` is outside the valid range
'''
if index < 0 or index >= len(self._items):
raise ValueError(f"The {index=} is not inside the items list")
self.removeItem(item=self._items[index])
self.insertItem(item=item,index=index)
[docs]
def addItem(self, item):
'''Append a layout item.
:param item: item to append
:type item: :py:class:`TTkLayoutItem`
'''
self.insertItems(len(self._items),[item])
[docs]
def addItems(self, items):
'''Append multiple layout items.
:param items: items to append
:type items: list[:py:class:`TTkLayoutItem`]
'''
self.insertItems(len(self._items),items)
[docs]
def insertItem(self, index, item):
'''Insert a single item at ``index``.
:param index: insertion index
:type index: int
:param item: item to insert
:type item: :py:class:`TTkLayoutItem`
'''
return self.insertItems(index,[item])
[docs]
def insertItems(self, index, items):
'''Insert multiple items at ``index`` and re-parent them.
Widgets passed directly are converted to their associated
:py:class:`TTkWidgetItem` wrapper before insertion.
:param index: insertion index
:type index: int
:param items: items or widgets to insert
:type items: list
'''
normalizedItems = list(items)
for i,item in enumerate(normalizedItems):
if not isinstance(widget:=item, TTkLayoutItem):
parent_widget = widget.parentWidget()
if parent_widget and parent_widget.layout():
parent_widget.layout().removeWidget(widget)
normalizedItems[i] = widget.widgetItem()
elif isinstance(widget_item:=item, TTkWidgetItem):
widget = widget_item.widget()
parent_widget = widget.parentWidget()
if parent_widget and (pl := parent_widget.layout()) and pl is not self:
pl.removeItem(widget_item)
elif (parent_layout := widget_item.parent()) and parent_layout is not self:
parent_layout.removeItem(widget_item)
elif isinstance(layout_item:=item, TTkLayout):
parent_widget = layout_item.parentWidget()
if parent_widget and (pl := parent_widget.layout()) and pl is not self:
pl.removeItem(layout_item)
elif (parent_layout := layout_item.parent()) and parent_layout is not self:
parent_layout.removeItem(layout_item)
self._items[index:index] = normalizedItems
self._zSortItems()
#self.update()
parent_widget = self.parentWidget()
for item in normalizedItems:
item.setParent(self)
if isinstance(item, TTkWidgetItem):
item.widget().setParent(parent_widget)
if parent_widget and parent_widget.isVisible():
parent_widget.update(repaint=True, updateLayout=True)
self.update()
[docs]
def removeItem(self, item):
'''Remove a single layout item.
:param item: item to remove
:type item: :py:class:`TTkLayoutItem`
'''
self.removeItems([item])
[docs]
def clear(self) -> None:
'''Remove and detach all items from this layout.'''
for item in self._items:
if isinstance(item, TTkWidgetItem):
item.widget().setParent(None)
item.setParent(None)
self._items = []
self._zSortItems()
[docs]
def removeItems(self, items):
'''Remove a list of layout items if present.
:param items: items to remove
:type items: list[:py:class:`TTkLayoutItem`]
'''
for item in items.copy():
if item in self._items:
self._items.remove(item)
if isinstance(item, TTkWidgetItem):
item.widget().setParent(None)
item.setParent(None)
self._zSortItems()
def _findBranchWidget(self, widget):
'''Find the direct branch item containing ``widget``.
:param widget: widget to search in the layout tree
:type widget: :py:class:`TTkWidget`
:return: direct child branch that contains the widget
:rtype: :py:class:`TTkLayoutItem` or None
'''
for item in self._items:
if isinstance(item, TTkLayout):
if item._findBranchWidget(widget) is not None:
return item
else:
if item.widget() == widget:
return item
return None
[docs]
def setGeometry(self, x, y, w, h):
'''Set layout geometry and propagate a layout update when changed.
:param x: horizontal position
:type x: int
:param y: vertical position
:type y: int
:param w: width
:type w: int
:param h: height
:type h: int
'''
ax, ay, aw, ah = self.geometry()
if ax==x and ay==y and aw==w and ah==h: return
TTkLayoutItem.setGeometry(self, x, y, w, h)
self.update(repaint=True, updateLayout=True)
[docs]
def update(self, *args, **kwargs) -> None:
'''Propagate update requests to child widgets and nested layouts.'''
for i in self._items:
if isinstance(i, TTkWidgetItem) and (_wid:=i._widget):
_wid.update(*args, **kwargs)
elif isinstance(i, TTkLayout):
i.update(*args, **kwargs)
[docs]
def layoutItemType(self) -> TTkK.LayoutItemTypes:
'''Return :py:attr:`TTkK.LayoutItemTypes.LayoutItem`.'''
return TTkK.LayoutItemTypes.LayoutItem