Source code for TermTk.TTkWidgets.tabwidget

# 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.

from __future__ import annotations

__all__ = ['TTkTabButton', 'TTkTabBar', 'TTkTabWidget', 'TTkBarType']

from enum import Enum
from dataclasses import dataclass
from typing import List, Tuple, Optional, Any, Dict

from TermTk.TTkCore.constant import TTkK
from TermTk.TTkCore.helper import TTkHelper
from TermTk.TTkCore.log import TTkLog
from TermTk.TTkCore.cfg import TTkCfg
from TermTk.TTkCore.color import TTkColor
from TermTk.TTkCore.canvas import TTkCanvas
from TermTk.TTkCore.string import TTkString, TTkStringType
from TermTk.TTkCore.signal import pyTTkSlot, pyTTkSignal
from TermTk.TTkCore.TTkTerm.inputkey import TTkKeyEvent
from TermTk.TTkCore.TTkTerm.inputmouse import TTkMouseEvent

from TermTk.TTkGui.drag import TTkDrag, TTkDnDEvent

from TermTk.TTkWidgets.widget import TTkWidget
from TermTk.TTkWidgets.container import TTkContainer
from TermTk.TTkWidgets.spacer import TTkSpacer
from TermTk.TTkWidgets.frame import TTkFrame
from TermTk.TTkWidgets.menubar import TTkMenuBarButton

from TermTk.TTkLayouts.boxlayout import TTkHBoxLayout
from TermTk.TTkLayouts.gridlayout import TTkGridLayout

[docs] class TTkBarType(Enum): NONE = 0x00 DEFAULT_3 = 0x01 DEFAULT_2 = 0x02 NERD_1 = 0x04
[docs] def vSize(self) -> int: return { TTkBarType.DEFAULT_3:3, TTkBarType.DEFAULT_2:2, TTkBarType.NERD_1:1}.get(self,3)
[docs] def offY(self) -> int: return { TTkBarType.DEFAULT_3:1, TTkBarType.DEFAULT_2:0, TTkBarType.NERD_1:0}.get(self,1)
class _TTkTabStatus(): __slots__ = ( "statusUpdated", "currentChanged", "tabBar", "tabButtons", "barType", "currentIndex", "highlighted") statusUpdated:pyTTkSignal tabBar:TTkTabBar tabButtons:List[TTkTabButton] barType:TTkBarType highlighted:Optional[int] currentIndex:int def __init__( self, tabBar:TTkTabBar, barType:TTkBarType): self.tabBar = tabBar self.barType = barType self.statusUpdated = pyTTkSignal() self.currentChanged = pyTTkSignal(int) self.tabButtons = [] self.highlighted = None self.currentIndex = -1 @pyTTkSlot() def _moveToTheLeft(self) -> None: self._setCurrentIndex(self.currentIndex-1) @pyTTkSlot() def _andMoveToTheRight(self) -> None: self._setCurrentIndex(self.currentIndex+1) @pyTTkSlot() def _highlightToTheRight(self) -> None: if self.highlighted is None: self.highlighted = self.currentIndex self.highlighted = min(self.highlighted+1,len(self.tabButtons)-1) self.statusUpdated.emit() @pyTTkSlot() def _andHighlightToTheLeft(self) -> None: if self.highlighted is None: self.highlighted = self.currentIndex self.highlighted = max(self.highlighted-1,0) self.statusUpdated.emit() # # @pyTTkSlot(TTkTabButton) # def _setCurrentButton(self, button:TTkTabButton) -> None: # '''setCurrentButton''' # index = self.tabButtons.index(button) # self._setCurrentIndex(index) @pyTTkSlot(int) def _setCurrentIndex(self, index) -> None: '''setCurrentIndex''' if ( ( 0 <= index < len(self.tabButtons) ) and ( self.currentIndex != index or self.highlighted != -1 ) ): self.highlighted = None if (self.currentIndex != index): self.currentIndex = index self.currentChanged.emit(index) self.statusUpdated.emit() @pyTTkSlot(int) def _resetHighlighted(self) -> None: if self.highlighted != -1: self.highlighted = None self.statusUpdated.emit() def _insertButton(self, index:int, button:TTkTabButton) -> None: self.tabButtons.insert(index,button) self.statusUpdated.connect(button.update) if index <= self.currentIndex: self.currentIndex += 1 self.currentChanged.emit(self.currentIndex) if self.currentIndex < 0: self.currentIndex = 0 self.currentChanged.emit(0) def _popButton(self, index:int) -> Optional[TTkTabButton]: if 0 <= index < len(self.tabButtons): button = self.tabButtons.pop(index) self.statusUpdated.disconnect(button.update) self.highlighted = None if self.currentIndex >= index: self.currentIndex -= 1 self.currentChanged.emit(self.currentIndex) self.statusUpdated.emit() return button return None _tabGlyphs = { 'scroller': ['◀','▶'], 'border' : { TTkBarType.DEFAULT_3 : [], TTkBarType.DEFAULT_2 : [], # 0 1 2 3 4 5 TTkBarType.NERD_1 : ['🭛','🭦','🭡','🭖','╱','╲'], } } _tabStyle:Dict[str,Any] = { 'default': {'color': TTkColor.fgbg("#dddd88","#000044"), 'bgColor': TTkColor.fgbg("#000000","#8888aa"), 'borderColor': TTkColor.RST, 'borderHighlightColors': { 'main' : TTkColor.fg('#00FFFF'), 'fade' : TTkColor.fg('#88FF88'), }, 'scrollerColors': { 'default': TTkColor.fg('#BBBBBB'), 'highlight': TTkColor.fg('#00FFFF'), 'inactive': TTkColor.fg('#888888'), }, 'glyphs':_tabGlyphs}, 'disabled': {'color': TTkColor.fg('#888888'), 'borderColor':TTkColor.fg('#888888')}, 'focus': {'color': TTkColor.fgbg("#dddd88","#000044")+TTkColor.BOLD, 'borderColor': TTkColor.fg("#ffff00") + TTkColor.BOLD}, } _tabStyleNormal = { 'default': {'borderColor': TTkColor.RST}, 'disabled': {'borderColor': TTkColor.fg('#888888')}, 'focus': {'borderColor': TTkColor.RST}, } _tabStyleFocussed = { 'default': {'borderColor': TTkColor.fg("#ffff00") + TTkColor.BOLD}, 'disabled': {'borderColor': TTkColor.fg('#888888')}, 'focus': {'borderColor': TTkColor.fg("#ffff00") + TTkColor.BOLD}, } class _TTkTabWidgetDragData(): __slots__ = ('_tabButton', '_tabWidget') def __init__(self, b:TTkTabButton, tw:TTkTabWidget) -> None: self._tabButton = b self._tabWidget = tw def tabButton(self) -> TTkTabButton: return self._tabButton def tabWidget(self) -> TTkTabWidget: return self._tabWidget class _TTkNewTabWidgetDragData(): __slots__ = ('_label', '_widget', '_closable', '_data') def __init__(self, label: TTkString, widget: TTkWidget, data: Any = None, closable: bool = False) -> None: self._data = data self._label = label self._widget = widget self._closable = closable def data(self) -> Any: return self._data def label(self) -> TTkString: return self._label def widget(self) -> TTkWidget: return self._widget def closable(self) -> bool: return self._closable class _TTkTabBarDragData(): __slots__ = ('_tabButton','_tabBar') def __init__(self, b: TTkTabButton, tb: TTkTabBar) -> None: self._tabButton:TTkTabButton = b self._tabBar:TTkTabBar = tb def tabButton(self) -> TTkTabButton: return self._tabButton def tabBar(self) -> TTkTabBar: return self._tabBar # class _TTkTabColorButton(TTkContainer): class _TTkTabColorButton(TTkWidget): classStyle = _tabStyle | { 'hover': { 'color': TTkColor.fgbg("#dddd88","#000050")+TTkColor.BOLD, 'bgColor': TTkColor.fgbg("#007771","#8888aa")+TTkColor.BOLD, 'borderColor': TTkColor.fg("#AAFFFF")+TTkColor.BOLD }, } __slots__ = ( '_tabStatus', # Signals 'tcbClicked' ) _tabStatus:_TTkTabStatus tcbClicked:pyTTkSignal def __init__(self, *, tabStatus:_TTkTabStatus, **kwargs) -> None: self.tcbClicked = pyTTkSignal(_TTkTabColorButton) self._tabStatus = tabStatus super().__init__(**kwargs) def mouseReleaseEvent(self, evt:TTkMouseEvent) -> bool: self.tcbClicked.emit(self) return True def keyEvent(self, evt:TTkKeyEvent) -> bool: if ( evt.type == TTkK.Character and evt.key==" " ) or \ ( evt.type == TTkK.SpecialKey and evt.key == TTkK.Key_Enter ): self._keyPressed = True self._pressed = True self.update() self.tcbClicked.emit(self) return True return False
[docs] class TTkTabButton(_TTkTabColorButton): classStyle = ( _TTkTabColorButton.classStyle | { 'default': _TTkTabColorButton.classStyle['default'] | {'closeGlyph':' □ '} , 'hover': _TTkTabColorButton.classStyle['hover'] | {'closeGlyph':' x '} } ) '''TTkTabButton''' __slots__ = ( '_data','_sideEnd', '_buttonStatus', '_closable', 'closeClicked', '_closeButtonPressed', '_text') def __init__(self, *, text:TTkString='', data:object=None, closable:bool=False, **kwargs) -> None: self._text = TTkString(text.replace('\n','')) self._sideEnd = TTkK.NONE self._buttonStatus = TTkK.Unchecked self._data = data self._closable = closable self.closeClicked = pyTTkSignal() super().__init__(**kwargs) self._closeButtonPressed = False self._resetSize() def _resetSize(self) -> None: style = self.currentStyle() size = self.text().termWidth() + 2 if self._closable: size += len(style['closeGlyph']) self.resize(size, self._tabStatus.barType.vSize()) self.setMinimumSize(size, self._tabStatus.barType.vSize()) self.setMaximumSize(size, self._tabStatus.barType.vSize())
[docs] def text(self) -> TTkString: return self._text
[docs] def setText(self, text:TTkString) -> None: self._text = TTkString(text.replace('\n','')) self._resetSize() self.update()
[docs] def data(self) -> Any: return self._data
[docs] def setData(self, data: Any) -> None: self._data=data
[docs] def setSideEnd(self, sideEnd: int) -> None: self._sideEnd = sideEnd self.update()
[docs] def buttonStatus(self) -> TTkK.CheckState: return self._buttonStatus
[docs] def setButtonStatus(self, status: TTkK.CheckState) -> None: self._buttonStatus = status self.update()
# This is a hack to force the action aftet the keypress # And not key release as normally happen to the button def mousePressEvent(self, evt:TTkMouseEvent) -> bool: x,y = evt.x,evt.y w,h = self.size() self._closeButtonPressed = False if self._closable and evt.key == TTkK.MidButton: self.closeClicked.emit() return True offY = self._tabStatus.barType.offY() if self._closable and y == offY and w-4<=x<w-1: self._closeButtonPressed = True return True return super().mouseReleaseEvent(evt) def mouseReleaseEvent(self, evt:TTkMouseEvent) -> bool: x,y = evt.x,evt.y w,h = self.size() offY = self._tabStatus.barType.offY() if self._closable and y == offY and w-4<=x<w-1 and self._closeButtonPressed: self._closeButtonPressed = False self.closeClicked.emit() return False self._closeButtonPressed = False return False def mouseDragEvent(self, evt:TTkMouseEvent) -> bool: drag = TTkDrag() self._closeButtonPressed = False if tb := self.parentWidget(): if isinstance(tb, TTkTabBar): if tw:= tb.parentWidget(): # Init the drag only if used in a tabBar/tabWidget if isinstance(tw, TTkTabWidget): data = _TTkTabWidgetDragData(self, tw) else: data = _TTkTabBarDragData(self, tb) pm = TTkCanvas(width=self.width(),height=3) pm.drawBox(pos=(0,0),size=(self.width(),3)) pm.drawText(pos=(1,1), text=self.text(), color=self.currentStyle()['color']) drag.setPixmap(pm) # drag.setPixmap(self) drag.setData(data) drag.exec() return True return super().mouseDragEvent(evt) def paintEvent(self, canvas: TTkCanvas) -> None: style = self.currentStyle() borderColor:TTkColor = style['borderColor'] textColor:TTkColor = style['color'] borderHighlightColors:TTkColor = style['borderHighlightColors'] w,h = self.size() offY = self._tabStatus.barType.offY() self_index = self._tabStatus.tabButtons.index(self) is_selected = self_index == self._tabStatus.currentIndex is_highlighted = self_index == self._tabStatus.highlighted tt = TTkCfg.theme.tab label = ' '*(w-2) if self._tabStatus.barType == TTkBarType.DEFAULT_3: # Selected HighLighted # ┌─────────╔═════════╗──────────────╭─────────╮──────────────┐─────────┐ # │Label 1.1║Label 1.2║Label Test 1.3│Label 1.4│Label Test 1.5│Label 1.6│ # ╞═════════╩═════════╩══════════════╧═════════╧════════════════════════╡ if is_highlighted: borderColor1_1 = borderHighlightColors['main'] borderColor1_2 = borderHighlightColors['fade'] borderColor1_3 = borderColor else: borderColor1_1 = borderColor borderColor1_2 = borderColor borderColor1_3 = borderColor if is_selected: # ╔═════════╗ ╔═════════╗ ╔═════════╗ # ╿Label 1.1║ ║Label 1.2║ ║Label 1.6╿ # ╞═════════╩ ╩═════════╩ ╩═════════╡ txtTop = tt[4] + tt[5] *(w-2) + tt[6] cLeft = tt[33] if self._sideEnd & TTkK.LEFT else tt[10] cRight = tt[33] if self._sideEnd & TTkK.RIGHT else tt[10] txtCenter = cLeft + label + cRight bLeft = tt[11] if self._sideEnd & TTkK.LEFT else tt[14] bRight = tt[15] if self._sideEnd & TTkK.RIGHT else tt[14] txtBottom = bLeft + tt[12]*(w-2) + bRight elif is_highlighted: # ╭─────────╮ ╭─────────╮ ╭─────────╮ # │Label 1.1│ │Label 1.2│ │Label 1.6│ # ╞═════════╧ ╧═════════╧ ╧═════════╡ # Initial txtTop = tt[7] + tt[1] *(w-2) + tt[8] txtCenter = tt[9] + label + tt[9] bLeft = tt[11] if self._sideEnd & TTkK.LEFT else tt[13] bRight = tt[15] if self._sideEnd & TTkK.RIGHT else tt[13] txtBottom = bLeft + tt[12]*(w-2) + bRight else: # ┌─────────┐ ┌─────────┐ ┌─────────┐ # │Label 1.1│ │Label 1.2│ │Label 1.6│ # ╞══════════ ═══════════ ══════════╡ txtTop = tt[0] + tt[1] *(w-2) + tt[3] txtCenter = tt[9] + label + tt[9] bLeft = tt[11] if self._sideEnd & TTkK.LEFT else tt[12] bRight = tt[15] if self._sideEnd & TTkK.RIGHT else tt[12] txtBottom = bLeft + tt[12]*(w-2) + bRight canvas.drawText(pos=(0,0),color=borderColor1_1,text=txtTop) canvas.drawText(pos=(0,1),color=borderColor1_2,text=txtCenter) canvas.drawText(pos=(0,2),color=borderColor1_3,text=txtBottom) elif self._tabStatus.barType == TTkBarType.DEFAULT_2: # Selected HighLighted # │Label 2.1║Label 2.2║Label Test 2.3│Label 2.4│Label Test 2.5│Label 2.6│ # └─────────╚═════════╝──────────────└─────────┘──────────────┘─────────┘ if is_highlighted: borderColor2_1 = borderHighlightColors['main'] borderColor2_2 = borderHighlightColors['fade'] else: borderColor2_1 = borderColor borderColor2_2 = borderColor if is_selected: # ║Label 2.1║ # ╚═════════╝ txtCenter = tt[10] + label + tt[10] txtBottom = tt[21] + tt[5] *(w-2) + tt[22] elif is_highlighted: # │Label 2.1│ # ╰─────────╯ txtCenter = tt[9] + label + tt[9] txtBottom = tt[23] + tt[19]*(w-2) + tt[24] else: # │Label 2.1│ # └─────────┘ txtCenter = tt[9] + label + tt[9] txtBottom = tt[18] + tt[19]*(w-2) + tt[20] canvas.drawText(pos=(0,0),color=borderColor2_2,text=txtCenter) canvas.drawText(pos=(0,1),color=borderColor2_1,text=txtBottom) elif self._tabStatus.barType == TTkBarType.NERD_1: # 🭛Label 5.1🭦 ╱Label Test 5.3╲ bgColor:TTkColor = style['bgColor'] glyphs = style['glyphs']['border'][self._tabStatus.barType] if is_selected: if is_highlighted: textColor += TTkColor.CYAN selectedBgColor = textColor.background() if self._sideEnd & TTkK.LEFT: _l = TTkString(' ',selectedBgColor) else: _l = TTkString(glyphs[0],selectedBgColor+bgColor.invertFgBg().foreground()) if self._sideEnd & TTkK.RIGHT: _r = TTkString(' ',selectedBgColor) else: _r = TTkString(glyphs[1],selectedBgColor+bgColor.invertFgBg().foreground()) txtCenter = _l + label + _r canvas.drawText(pos=(0,0),color=selectedBgColor,text=txtCenter) elif is_highlighted: highlightedBgColor = borderHighlightColors['fade'].invertFgBg().background() selectedColor = textColor.background().invertFgBg() textColor = TTkColor.BLUE+ highlightedBgColor _left_selected = ( self_index-1 ) == self._tabStatus.currentIndex != -1 _right_selected = ( self_index+1 ) == self._tabStatus.currentIndex if self._sideEnd & TTkK.LEFT: _l = TTkString(' ',highlightedBgColor) else: if _left_selected: _l = TTkString(glyphs[0],selectedColor) else: _l = TTkString(glyphs[0],highlightedBgColor+bgColor.invertFgBg().foreground()) if self._sideEnd & TTkK.RIGHT: _r = TTkString(' ',highlightedBgColor) else: if _right_selected: _r = TTkString(glyphs[1],selectedColor) else: _r = TTkString(glyphs[1],highlightedBgColor+bgColor.invertFgBg().foreground()) txtCenter = _l + label + _r canvas.drawText(pos=(0,0),color=highlightedBgColor,text=txtCenter) else: textColor = bgColor if self._sideEnd & TTkK.LEFT: _l = TTkString(' ',bgColor) else: _l = TTkString(glyphs[4],bgColor) if self._sideEnd & TTkK.RIGHT: _r = TTkString(' ',bgColor) else: _r = TTkString(glyphs[5],bgColor) txtCenter = _l + label + _r canvas.drawText(pos=(0,0),color=borderColor,text=txtCenter) canvas.drawText(pos=(1,offY), text=self.text(), color=textColor) if self._closable: closeGlyph = style['closeGlyph'] closeOff = len(closeGlyph) canvas.drawText(pos=(w-closeOff-1,offY), text=closeGlyph, color=textColor)
class _TTkTabMenuButton(TTkMenuBarButton): def paintEvent(self, canvas: TTkCanvas) -> None: style = self.currentStyle() borderColor = style['borderColor'] textColor = style['color'] text = TTkString('[',borderColor) + TTkString(self.text(),textColor) + TTkString(']',borderColor) canvas.drawText(pos=(0,0),text=text) class _TTkTabScrollerButton(_TTkTabColorButton): classStyle = _tabStyle __slots__ = ('_side', '_sideEnd', '_scrollerStatus') def __init__(self, *, side:int=TTkK.LEFT, **kwargs) -> None: self._side = side self._sideEnd = side super().__init__(**kwargs) self.resize(2, self._tabStatus.barType.vSize()) self.setMinimumSize(2, self._tabStatus.barType.vSize()) self.setMaximumSize(2, self._tabStatus.barType.vSize()) def setScrollerStatus(self, status) -> None: if status != self._scrollerStatus: self._scrollerStatus = status self.update() def setSideEnd(self, sideEnd: int) -> None: self._sideEnd = sideEnd self.update() # This is a hack to force the action aftet the keypress # And not key release as normally happen to the button def mousePressEvent(self, evt:TTkMouseEvent) -> bool: return super().mouseReleaseEvent(evt) def mouseReleaseEvent(self, evt:TTkMouseEvent) -> bool: return False def mouseTapEvent(self, evt:TTkMouseEvent) -> bool: self.tcbClicked.emit(self) return True def paintEvent(self, canvas:TTkCanvas) -> None: style = self.currentStyle() glyphs = style['glyphs']['scroller'] scrollerColors = style['scrollerColors'] borderColor = style['borderColor'] arrowColor:TTkColor = scrollerColors['default'] if self._tabStatus.highlighted is None: pass elif ( self._side == TTkK.LEFT and self._tabStatus.highlighted == 0 ): arrowColor = scrollerColors['inactive'] elif ( self._side == TTkK.RIGHT and self._tabStatus.highlighted >= len(self._tabStatus.tabButtons)-1 ): arrowColor = scrollerColors['inactive'] else: arrowColor = scrollerColors['highlight'] tt = TTkCfg.theme.tab if self._tabStatus.barType == TTkBarType.DEFAULT_3: lse = tt[11] if self._sideEnd & TTkK.LEFT else tt[13] rse = tt[15] if self._sideEnd & TTkK.RIGHT else tt[13] if self._side == TTkK.LEFT: # Draw Border canvas.drawText(pos=(0,0), color=borderColor, text=tt[7] +tt[1]) canvas.drawText(pos=(0,1), color=borderColor, text=tt[9] ) canvas.drawText(pos=(0,2), color=borderColor, text=lse +tt[12]) # Draw Arrow canvas.drawChar(pos=(1,1), char=glyphs[0], color=arrowColor) else: # Draw Border canvas.drawText(pos=(0,0), color=borderColor, text=tt[1] +tt[8]) canvas.drawText(pos=(1,1), color=borderColor, text= tt[9]) canvas.drawText(pos=(0,2), color=borderColor, text=tt[12]+rse) # Draw Arrow canvas.drawChar(pos=(0,1), char=glyphs[1], color=arrowColor) elif self._tabStatus.barType == TTkBarType.DEFAULT_2: if self._side == TTkK.LEFT: # Draw Border canvas.drawText(pos=(0,0), color=borderColor, text=tt[9] +tt[31]) canvas.drawText(pos=(0,1), color=borderColor, text=tt[23]+tt[1]) # Draw Arrow canvas.drawChar(pos=(1,0), char=glyphs[0], color=arrowColor) else: # Draw Border canvas.drawText(pos=(0,0), color=borderColor, text=tt[32]+tt[9]) canvas.drawText(pos=(0,1), color=borderColor, text=tt[1] +tt[24]) # Draw Arrow canvas.drawChar(pos=(0,0), char=glyphs[1], color=arrowColor) elif self._tabStatus.barType == TTkBarType.NERD_1: if self._side == TTkK.LEFT: canvas.drawText(pos=(0,0),color=style['bgColor']+arrowColor,text=f" {glyphs[0]}") else: canvas.drawText(pos=(0,0),color=style['bgColor']+arrowColor,text=f"{glyphs[1]} ") ''' _curentIndex = 2 _tabButtons = [0],[1], [2], [3], [4], ╭─┌──┌──────╔══════╗──────┬──────┐─╮ _labels= │◀│La│Label1║Label2║Label3│Label4│▶│ ╞═══════════╩══════╩═══════════════╡ leftscroller rightScroller '''
[docs] class TTkTabBar(TTkContainer): '''TTkTabBar''' classStyle = _tabStyle __slots__ = ( '_tabStatus', '_tabMovable', '_leftScroller', '_rightScroller', '_tabClosable', '_sideEnd', #Signals 'currentChanged', 'tabBarClicked', 'tabCloseRequested') currentChanged: pyTTkSignal tabBarClicked: pyTTkSignal tabCloseRequested: pyTTkSignal _tabStatus:_TTkTabStatus _tabMovable:bool _tabClosable:bool _sideEnd:int _tabStatus:_TTkTabStatus _leftScroller:_TTkTabScrollerButton _rightScroller:_TTkTabScrollerButton def __init__(self, *, closable:bool=False, small:bool=True, barType:TTkBarType=TTkBarType.NONE, **kwargs) -> None: self.tabBarClicked = pyTTkSignal(int) self.tabCloseRequested = pyTTkSignal(int) self._tabStatus = _TTkTabStatus( tabBar = self, barType = barType, ) self.currentChanged = self._tabStatus.currentChanged self._tabMovable = False self._tabClosable = closable self._sideEnd = TTkK.LEFT | TTkK.RIGHT if barType == TTkBarType.NONE: self._tabStatus.barType = TTkBarType.DEFAULT_2 if small else TTkBarType.DEFAULT_3 self._leftScroller = _TTkTabScrollerButton(tabStatus=self._tabStatus,side=TTkK.LEFT) self._rightScroller = _TTkTabScrollerButton(tabStatus=self._tabStatus,side=TTkK.RIGHT) self._leftScroller.tcbClicked.connect( self._tabStatus._moveToTheLeft) self._rightScroller.tcbClicked.connect(self._tabStatus._andMoveToTheRight) super().__init__(forwardStyle=False, **kwargs) # Add and connect the scrollers self.layout().addWidget(self._leftScroller) self.layout().addWidget(self._rightScroller) self.setFocusPolicy(TTkK.ParentFocus) self._tabStatus.statusUpdated.connect(self._updateTabs) self._tabStatus.statusUpdated.connect(self._leftScroller.update) self._tabStatus.statusUpdated.connect(self._rightScroller.update) def mergeStyle(self, style: Dict) -> None: super().mergeStyle(style) for t in self._tabStatus.tabButtons: t.mergeStyle(style) self._leftScroller.mergeStyle(style) self._rightScroller.mergeStyle(style)
[docs] def sideEnd(self) -> int: return self._sideEnd
[docs] def setSideEnd(self, sideEnd: int) -> None: self._sideEnd = sideEnd self._rightScroller.setSideEnd(sideEnd&TTkK.RIGHT) self._leftScroller.setSideEnd(sideEnd&TTkK.LEFT) self._updateTabs()
[docs] def addTab(self, label, data=None, closable=None) -> int: '''addTab''' return self.insertTab(len(self._tabStatus.tabButtons), label=label, data=data, closable=closable)
[docs] def insertTab(self, index, label, data=None, closable=None) -> int: '''insertTab''' button = TTkTabButton(parent=self, text=label, tabStatus=self._tabStatus, closable=self._tabClosable if closable is None else closable, data=data) self._tabStatus._insertButton(index,button) button.tcbClicked.connect(self._tcbClickedHandler) button.closeClicked.connect(lambda :self.tabCloseRequested.emit(self._tabStatus.tabButtons.index(button))) self._updateTabs() return index
@pyTTkSlot(TTkTabButton) def _tcbClickedHandler(self, btn: TTkTabButton) -> None: index = self._tabStatus.tabButtons.index(btn) self.tabBarClicked.emit(index) self.setCurrentIndex(index)
[docs] @pyTTkSlot(int) def removeTab(self, index:int) -> None: '''removeTab''' if not (button := self._tabStatus._popButton(index)): return button.tcbClicked.clear() button.closeClicked.clear() self.layout().removeWidget(button) self._updateTabs()
[docs] def currentData(self) -> Any: return self.tabData(self._tabStatus.currentIndex)
[docs] def tabButton(self, index: int) -> Optional[TTkTabButton]: '''tabButton''' if 0 <= index < len(self._tabStatus.tabButtons): return self._tabStatus.tabButtons[index] return None
[docs] def tabData(self, index: int) -> Any: '''tabData''' if 0 <= index < len(self._tabStatus.tabButtons): return self._tabStatus.tabButtons[index].data() return None
[docs] def setTabData(self, index: int, data: Any) -> None: '''setTabData''' self._tabStatus.tabButtons[index].setData(data)
[docs] def tabsClosable(self) -> bool: '''tabsClosable''' return self._tabClosable
[docs] def setTabsClosable(self, closable: bool) -> None: '''setTabsClosable''' self._tabClosable = closable
[docs] def currentIndex(self) -> int: '''currentIndex''' return self._tabStatus.currentIndex
[docs] @pyTTkSlot(int) def setCurrentIndex(self, index: int) -> None: '''setCurrentIndex''' self._tabStatus._setCurrentIndex(index)
def resizeEvent(self, w: int, h: int) -> None: self._updateTabs() def _updateTabs(self) -> None: w = self.width() # Find the tabs used size max size maxLen = 0 sizes = [t.width()-1 for t in self._tabStatus.tabButtons] for s in sizes: maxLen += s if maxLen <= w: self._leftScroller.hide() self._rightScroller.hide() shrink = 1 offx = 0 else: self._leftScroller.show() self._rightScroller.show() self._rightScroller.move(w-2,0) w-=4 shrink = w/maxLen offx = 2 self._leftScroller.update() self._rightScroller.update() posx=0 for t in self._tabStatus.tabButtons: tmpx = offx+min(int(posx*shrink),w-t.width()) sideEnd = TTkK.NONE if tmpx==0: sideEnd |= self.sideEnd() & TTkK.LEFT if tmpx+t.width()==self.width(): sideEnd |= self.sideEnd() & TTkK.RIGHT t.move(tmpx,0) t.setSideEnd(sideEnd) posx += t.width()-1 # ZReorder the widgets: for i in range(0,max(0,self._tabStatus.currentIndex)): self._tabStatus.tabButtons[i].raiseWidget() for i in reversed(range(max(0,self._tabStatus.currentIndex),len(self._tabStatus.tabButtons))): self._tabStatus.tabButtons[i].raiseWidget() # set the buttons text color based on the selection/offset for i,b in enumerate(self._tabStatus.tabButtons): if i == self._tabStatus.highlighted != self._tabStatus.currentIndex: b.setButtonStatus(TTkK.PartiallyChecked) b.raiseWidget() elif i == self._tabStatus.currentIndex: b.setButtonStatus(TTkK.Checked) else: b.setButtonStatus(TTkK.Unchecked) self.update() def wheelEvent(self, evt:TTkMouseEvent) -> bool: if evt.evt in (TTkK.WHEEL_Up,TTkK.WHEEL_Left): self._tabStatus._moveToTheLeft() elif evt.evt in (TTkK.WHEEL_Down,TTkK.WHEEL_Right): self._tabStatus._andMoveToTheRight() return True def keyEvent(self, evt:TTkKeyEvent) -> bool: if evt.type == TTkK.SpecialKey: if evt.key == TTkK.Key_Right: self._tabStatus._highlightToTheRight() return True elif evt.key == TTkK.Key_Left: self._tabStatus._andHighlightToTheLeft() return True if ( evt.type == TTkK.Character and evt.key==" " ) or \ ( evt.type == TTkK.SpecialKey and evt.key == TTkK.Key_Enter ): self._tabStatus._setCurrentIndex(self._tabStatus.highlighted) return True return False def paintEvent(self, canvas): style = self.currentStyle() borderColor = style['borderColor'] w = self.width() tt = TTkCfg.theme.tab if self._tabStatus.barType == TTkBarType.DEFAULT_2: lse = tt[36] if self._sideEnd & TTkK.LEFT else tt[19] rse = tt[35] if self._sideEnd & TTkK.RIGHT else tt[19] canvas.drawText(pos=(0,1),text=lse + tt[19]*(w-2) + rse, color=borderColor) elif self._tabStatus.barType == TTkBarType.DEFAULT_3: lse = tt[11] if self._sideEnd & TTkK.LEFT else tt[12] rse = tt[15] if self._sideEnd & TTkK.RIGHT else tt[12] canvas.drawText(pos=(0,2),text=lse + tt[12]*(w-2) + rse, color=borderColor) elif self._tabStatus.barType == TTkBarType.NERD_1: # glyphs = style['glyphs']['border'][self._tabStatus.barType] canvas.fill(color=style['bgColor'])
# canvas.drawText(pos=(0,0),color=borderColor,text="-x----------------------------------------") ''' ┌────────────────────────────┐ │ Root Layout │ │┌────────┬────────┬────────┐│ ││ Left M │ TABS │ RightM ││ │└────────┴────────┴────────┘│ │┌──────────────────────────┐│ ││ Layout ││ ││ ││ │└──────────────────────────┘│ └────────────────────────────┘ ╭─┌──┌──────╔══════╗──────┬──────┐─╮ ┌[M1]┬[M2]┤◀│La│Label1║Label2║Label3│Label4│▶│ ╞════╧════╧═══════════╩══════╩═══════════════╡ leftscroller rightScroller '''
[docs] class TTkTabWidget(TTkFrame): '''TTkTabWidget''' classStyle = _tabStyle __slots__ = ( '_tabStatus', '_tabBarTopLayout', '_topLeftLayout', '_topRightLayout', '_tabWidgets', '_spacer', # Forward Signals 'currentChanged', 'tabBarClicked', # forward methods 'tabsClosable', 'setTabsClosable', 'tabData', 'setTabData', 'currentData', 'currentIndex', 'setCurrentIndex', 'tabCloseRequested') _tabWidgets:List[TTkWidget] _tabStatus:_TTkTabStatus def __init__(self, *, closable:bool=False, barType:TTkBarType=TTkBarType.NONE, **kwargs) -> None: self._tabWidgets = [] self._tabBarTopLayout = TTkGridLayout() tabBar = TTkTabBar( barType=barType, closable=closable) self._tabStatus = tabBar._tabStatus super().__init__(forwardStyle=False, **kwargs) if barType == TTkBarType.NONE: self._tabStatus.barType = TTkBarType.DEFAULT_3 if self.border() else TTkBarType.DEFAULT_2 self._topLeftLayout = None self._topRightLayout = None self._tabStatus.tabBar.currentChanged.connect(self._tabChanged) self.setFocusPolicy(TTkK.ClickFocus | TTkK.TabFocus) self._spacer = TTkSpacer(parent=self) self.setLayout(TTkGridLayout()) if self._tabStatus.barType == TTkBarType.DEFAULT_3: self._tabBarTopLayout.addWidget(self._tabStatus.tabBar,0,1,3,1) self.setPadding(3,1,1,1) elif self._tabStatus.barType == TTkBarType.DEFAULT_2: self._tabBarTopLayout.addWidget(self._tabStatus.tabBar,0,1,2,1) self.setPadding(2,0,0,0) elif self._tabStatus.barType == TTkBarType.NERD_1: self._tabBarTopLayout.addWidget(self._tabStatus.tabBar,0,1,1,1) self.setPadding(1,0,0,0) self.rootLayout().addItem(self._tabBarTopLayout) self._tabBarTopLayout.setGeometry(0,0,self._width,self._padt) # forwarded methods self.currentIndex = self._tabStatus.tabBar.currentIndex self.setCurrentIndex = self._tabStatus.tabBar.setCurrentIndex self.tabData = self._tabStatus.tabBar.tabData self.setTabData = self._tabStatus.tabBar.setTabData self.currentData = self._tabStatus.tabBar.currentData self.tabsClosable = self._tabStatus.tabBar.tabsClosable self.setTabsClosable = self._tabStatus.tabBar.setTabsClosable # forwarded Signals self.currentChanged = self._tabStatus.tabBar.currentChanged self.tabBarClicked = self._tabStatus.tabBar.tabBarClicked self.tabCloseRequested = self._tabStatus.tabBar.tabCloseRequested self.tabBarClicked.connect(self.setFocus) self.focusChanged.connect(self._focusChanged) def _focusChanged(self, focus: bool) -> None: if focus: self._tabStatus.tabBar.mergeStyle(_tabStyleFocussed) else: self._tabStatus.highlighted = None self._tabStatus.tabBar.mergeStyle(_tabStyleNormal)
[docs] def count(self) -> int: return len(self._tabWidgets)
[docs] def indexOf(self, widget) -> int: if widget in self._tabWidgets: return self._tabWidgets.index(widget) return -1
[docs] def tabButton(self, index:int) -> TTkTabButton: '''tabButton''' return self._tabStatus.tabBar.tabButton(index)
[docs] def widget(self, index:int) -> Optional[TTkWidget]: '''widget''' if 0 <= index < len(self._tabWidgets): return self._tabWidgets[index] return None
[docs] def currentWidget(self) -> TTkWidget: '''currentWidget''' for w in self._tabWidgets: if w.isVisible(): return w return self._spacer
[docs] @pyTTkSlot(TTkWidget) def setCurrentWidget(self, widget:TTkWidget) -> None: '''setCurrentWidget''' for i, w in enumerate(self._tabWidgets): if widget == w: self.setCurrentIndex(i)
@pyTTkSlot(int) def _tabChanged(self, index:int) -> None: self._spacer.show() for i, widget in enumerate(self._tabWidgets): if index == i: widget.show() self._spacer.hide() else: widget.hide() def keyEvent(self, evt:TTkKeyEvent) -> bool: if self.hasFocus() and self._tabStatus.tabBar.keyEvent(evt=evt): return True return super().keyEvent(evt) def mousePressEvent(self, evt:TTkMouseEvent) -> bool: return True def mouseReleaseEvent(self, evt:TTkMouseEvent) -> bool: return True def mouseTapEvent(self, evt:TTkMouseEvent) -> bool: return True def _dropNewTab(self, x:int, y:int, data:_TTkNewTabWidgetDragData) -> None: w = data.widget() d = data.data() l = data.label() c = data.closable() if y < 3: tbx = self._tabStatus.tabBar.x() newIndex = 0 for b in self._tabStatus.tabButtons: if tbx+b.x()+b.width()/2 < x: newIndex += 1 self.insertTab(newIndex, w, l, d, c) self.setCurrentIndex(newIndex) else: self.addTab(w, l, d, c) self.setCurrentIndex(len(self._tabStatus.tabButtons)-1) def dropEvent(self, evt:TTkDnDEvent) -> bool: data = evt.data() x, y = evt.x, evt.y if not data: return False elif isinstance(data, _TTkTabWidgetDragData): tb = data.tabButton() tw = data.tabWidget() index = tw._tabStatus.tabButtons.index(tb) widget = tw.widget(index) data = tw.tabData(index) if TTkHelper.isParent(self, tw): return False if y < 3: tbx = self._tabStatus.tabBar.x() newIndex = 0 for b in self._tabStatus.tabButtons: if tbx+b.x()+b.width()/2 < x: newIndex += 1 if tw == self: if index <= newIndex: newIndex -= 1 tw.removeTab(index) self.insertTab(newIndex, widget, tb.text(), data, tb._closable) self.setCurrentIndex(newIndex) if self.hasFocus(): self._tabStatus.tabBar.mergeStyle(_tabStyleFocussed) else: self._tabStatus.tabBar.mergeStyle(_tabStyleNormal) #self._tabChanged(newIndex) elif tw != self: tw.removeTab(index) newIndex = len(self._tabWidgets) self.addTab(widget, tb.text(), data) self.setCurrentIndex(newIndex) self._tabChanged(newIndex) TTkLog.debug(f"Drop -> pos={evt.pos()}") return True elif isinstance(data,_TTkNewTabWidgetDragData): self._dropNewTab(x,y,data) TTkLog.debug(f"Drop -> pos={evt.pos()}") return True elif isinstance(data,list) and all(isinstance(_d,_TTkNewTabWidgetDragData) for _d in data): for _d in data: self._dropNewTab(x,y,_d) TTkLog.debug(f"Drop -> pos={evt.pos()}") return True return False
[docs] def addMenu(self, text, position=TTkK.LEFT, data=None) -> TTkMenuBarButton: '''addMenu''' button = _TTkTabMenuButton(text=text, data=data) self._tabStatus.tabBar.setSideEnd(self._tabStatus.tabBar.sideEnd() & ~position) if position==TTkK.LEFT: if not self._topLeftLayout: self._topLeftLayout = TTkHBoxLayout() self._tabBarTopLayout.addItem(self._topLeftLayout,1 if self.border() else 0,0) layout = self._topLeftLayout else: if not self._topRightLayout: self._topRightLayout = TTkHBoxLayout() self._tabBarTopLayout.addItem(self._topRightLayout,1 if self.border() else 0,2) layout = self._topRightLayout layout.addWidget(button) self._tabBarTopLayout.update() return button
[docs] def addTab(self, widget, label, data=None, closable=None) -> int: '''addTab''' widget.hide() self._tabWidgets.append(widget) self.layout().addWidget(widget) return self._tabStatus.tabBar.addTab(label, data, closable)
[docs] def insertTab(self, index, widget, label, data=None, closable=None) -> int: '''insertTab''' widget.hide() self._tabWidgets.insert(index, widget) self.layout().addWidget(widget) return self._tabStatus.tabBar.insertTab(index, label, data, closable)
[docs] @pyTTkSlot(int) def removeTab(self, index) -> None: '''removeTab''' self.layout().removeWidget(self._tabWidgets[index]) self._tabWidgets.pop(index) self._tabStatus.tabBar.removeTab(index)
def resizeEvent(self, w, h): self._tabBarTopLayout.setGeometry(0,0,w,self._padt) def paintEvent(self, canvas): style = self.currentStyle() borderColor = style['borderColor'] tt = TTkCfg.theme.tab if self.border(): canvas.drawBox(pos=(0,2),size=(self.width(),self.height()-2), color=borderColor, grid=9) else: canvas.drawText(pos=(0,1),text=tt[36] + tt[19]*(self.width()-2) + tt[35], color=borderColor)