# 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.
__all__ = ['TTkTabButton', 'TTkTabBar', 'TTkTabWidget']
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
from TermTk.TTkGui.drag import TTkDrag
from TermTk.TTkCore.signal import pyTTkSlot, pyTTkSignal
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.button import TTkButton
from TermTk.TTkWidgets.menubar import TTkMenuBarButton
from TermTk.TTkLayouts.boxlayout import TTkHBoxLayout
from TermTk.TTkLayouts.gridlayout import TTkGridLayout
_tabStyle = {
'default': {'color': TTkColor.fg("#dddd88")+TTkColor.bg("#000044"),
'borderColor': TTkColor.RST,
'tabOffsetColor': TTkColor.RST},
'disabled': {'color': TTkColor.fg('#888888'),
'borderColor':TTkColor.fg('#888888'),
'tabOffsetColor': TTkColor.RST},
'focus': {'color': TTkColor.fg("#dddd88")+TTkColor.bg("#000044")+TTkColor.BOLD,
'borderColor': TTkColor.fg("#ffff00") + TTkColor.BOLD,
'tabOffsetColor': TTkColor.RST},
}
_tabStyleNormal = {
'default': {'borderColor': TTkColor.RST},
}
_tabStyleFocussed = {
'default': {'borderColor': TTkColor.fg("#ffff00") + TTkColor.BOLD},
}
class _TTkTabWidgetDragData():
__slots__ = ('_tabButton', '_tabWidget')
def __init__(self, b, tw):
self._tabButton = b
self._tabWidget = tw
def tabButton(self): return self._tabButton
def tabWidget(self): return self._tabWidget
class _TTkTabBarDragData():
__slots__ = ('_tabButton','_tabBar')
def __init__(self, b, tb):
self._tabButton = b
self._tabBar = tb
def tabButton(self): return self._tabButton
def tabBar(self): return self._tabBar
class _TTkTabColorButton(TTkContainer):
classStyle = _tabStyle | {
'hover': {'color': TTkColor.fg("#dddd88")+TTkColor.bg("#000050")+TTkColor.BOLD,
'borderColor': TTkColor.fg("#AAFFFF")+TTkColor.BOLD},
}
__slots__ = (
'_text', '_border',
# Signals
'clicked'
)
def __init__(self, *,
text:TTkString='',
border:bool=True,
**kwargs) -> None:
self.clicked = pyTTkSignal()
self._text = TTkString(text.replace('\n',''))
self._border = border
super().__init__(forwardStyle=True, **kwargs)
def text(self) -> TTkString:
return self._text
def mouseReleaseEvent(self, evt):
self.clicked.emit()
return True
def keyEvent(self, evt):
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.clicked.emit()
return True
return False
class _TTkTabMenuButton(TTkMenuBarButton):
def paintEvent(self, canvas):
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')
def __init__(self, *,
side:int=TTkK.LEFT,
**kwargs) -> None:
self._side = side
self._sideEnd = self._side
super().__init__(**kwargs)
if self._border:
self.resize(2, 3)
self.setMinimumSize(2, 3)
self.setMaximumSize(2, 3)
else:
self.resize(2, 2)
self.setMinimumSize(2, 2)
self.setMaximumSize(2, 2)
self.setFocusPolicy(TTkK.ParentFocus)
def side(self):
return self._side
def setSide(self, side):
self._side = side
self.update()
def sideEnd(self):
return self._sideEnd
def setSideEnd(self, sideEnd):
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):
return super().mouseReleaseEvent(evt)
def mouseReleaseEvent(self, evt):
return False
def mouseTapEvent(self, evt) -> bool:
self.clicked.emit()
return True
def paintEvent(self, canvas):
style = self.currentStyle()
borderColor = style['borderColor']
offsetColor = style['tabOffsetColor']
# textColor = style['color']
tt = TTkCfg.theme.tab
if self._border:
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:
canvas.drawText(pos=(0,0), color=borderColor, text=tt[7] +tt[1])
canvas.drawText(pos=(0,1), color=borderColor, text=tt[9] +tt[31])
canvas.drawText(pos=(0,2), color=borderColor, text=lse +tt[12])
canvas.drawChar(pos=(1,1), char=tt[31], color=offsetColor)
else:
canvas.drawText(pos=(0,0), color=borderColor, text=tt[1] +tt[8])
canvas.drawText(pos=(0,1), color=borderColor, text=tt[32]+tt[9])
canvas.drawText(pos=(0,2), color=borderColor, text=tt[12]+rse)
canvas.drawChar(pos=(0,1), char=tt[32], color=offsetColor)
else:
if self._side == TTkK.LEFT:
canvas.drawText(pos=(0,0), color=borderColor, text=tt[9] +tt[31])
canvas.drawText(pos=(0,1), color=borderColor, text=tt[23]+tt[1])
canvas.drawChar(pos=(1,0), char=tt[31], color=offsetColor)
else:
canvas.drawText(pos=(0,0), color=borderColor, text=tt[32]+tt[9])
canvas.drawText(pos=(0,1), color=borderColor, text=tt[1] +tt[24])
canvas.drawChar(pos=(0,0), char=tt[32], color=offsetColor)
'''
_curentIndex = 2
_tabButtons = [0],[1], [2], [3], [4],
╭─┌──┌──────╔══════╗──────┬──────┐─╮
_labels= │◀│La│Label1║Label2║Label3│Label4│▶│
╞═══════════╩══════╩═══════════════╡
leftscroller rightScroller
'''
[docs]
class TTkTabBar(TTkContainer):
'''TTkTabBar'''
classStyle = _tabStyle
__slots__ = (
'_tabButtons', '_tabMovable', '_small',
'_highlighted', '_currentIndex','_lastIndex',
'_leftScroller', '_rightScroller',
'_tabClosable',
'_sideEnd',
#Signals
'currentChanged', 'tabBarClicked', 'tabCloseRequested')
def __init__(self, *,
closable:bool=False,
small:bool=True,
**kwargs) -> None:
self._tabButtons = []
self._currentIndex = -1
self._lastIndex = -1
self._highlighted = -1
self._tabMovable = False
self._tabClosable = closable
self._sideEnd = TTkK.LEFT | TTkK.RIGHT
self._small = small
self._leftScroller = _TTkTabScrollerButton(border=not self._small,side=TTkK.LEFT)
self._rightScroller = _TTkTabScrollerButton(border=not self._small,side=TTkK.RIGHT)
self._leftScroller.clicked.connect( self._moveToTheLeft)
self._rightScroller.clicked.connect(self._andMoveToTheRight)
super().__init__(forwardStyle=False, **kwargs)
# Add and connect the scrollers
self.layout().addWidget(self._leftScroller)
self.layout().addWidget(self._rightScroller)
# Signals
self.currentChanged = pyTTkSignal(int)
self.tabBarClicked = pyTTkSignal(int)
self.tabCloseRequested = pyTTkSignal(int)
self.setFocusPolicy(TTkK.ClickFocus + TTkK.TabFocus)
def mergeStyle(self, style):
super().mergeStyle(style)
for t in self._tabButtons:
t.mergeStyle(style)
self._leftScroller.mergeStyle(style)
self._rightScroller.mergeStyle(style)
[docs]
def sideEnd(self):
return self._sideEnd
[docs]
def setSideEnd(self, sideEnd):
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):
'''addTab'''
return self.insertTab(len(self._tabButtons), label=label, data=data, closable=closable)
[docs]
def insertTab(self, index, label, data=None, closable=None):
'''insertTab'''
if index <= self._currentIndex:
self._currentIndex += 1
button = TTkTabButton(parent=self, text=label, border=not self._small, closable=self._tabClosable if closable is None else closable, data=data)
self._tabButtons.insert(index,button)
button.clicked.connect(lambda :self.setCurrentIndex(self._tabButtons.index(button)))
button.clicked.connect(lambda :self.tabBarClicked.emit(self._tabButtons.index(button)))
button.closeClicked.connect(lambda :self.tabCloseRequested.emit(self._tabButtons.index(button)))
self._updateTabs()
return index
[docs]
@pyTTkSlot(int)
def removeTab(self, index):
'''removeTab'''
button = self._tabButtons[index]
button.clicked.clear()
button.closeClicked.clear()
self.layout().removeWidget(button)
self._tabButtons.pop(index)
if self._currentIndex == index:
self._lastIndex = -2
if self._currentIndex >= index:
self._currentIndex -= 1
self._highlighted = self._currentIndex
self._updateTabs()
[docs]
def currentData(self):
return self.tabData(self._currentIndex)
[docs]
def tabData(self, index):
'''tabData'''
if 0 <= index < len(self._tabButtons):
return self._tabButtons[index].data()
return None
[docs]
def setTabData(self, index, data):
'''setTabData'''
self._tabButtons[index].setData(data)
[docs]
def tabsClosable(self):
'''tabsClosable'''
return self._tabClosable
[docs]
def setTabsClosable(self, closable):
'''setTabsClosable'''
self._tabClosable = closable
[docs]
def currentIndex(self):
'''currentIndex'''
return self._currentIndex
[docs]
@pyTTkSlot(int)
def setCurrentIndex(self, index):
'''setCurrentIndex'''
TTkLog.debug(index)
if 0 <= index < len(self._tabButtons):
self._currentIndex = index
self._highlighted = index
self._updateTabs()
def resizeEvent(self, w, h):
self._updateTabs()
def _updateTabs(self):
w = self.width()
# Find the tabs used size max size
maxLen = 0
sizes = [t.width()-1 for t in self._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
posx=0
for t in self._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._currentIndex)):
self._tabButtons[i].raiseWidget()
for i in reversed(range(max(0,self._currentIndex),len(self._tabButtons))):
self._tabButtons[i].raiseWidget()
if self._currentIndex == -1:
self._currentIndex = len(self._tabButtons)-1
if self._lastIndex != self._currentIndex:
self._lastIndex = self._currentIndex
self.currentChanged.emit(self._currentIndex)
# set the buttons text color based on the selection/offset
for i,b in enumerate(self._tabButtons):
if i == self._highlighted != self._currentIndex:
b.setTabStatus(TTkK.PartiallyChecked)
b.raiseWidget()
elif i == self._currentIndex:
b.setTabStatus(TTkK.Checked)
else:
b.setTabStatus(TTkK.Unchecked)
self.update()
def _moveToTheLeft(self):
self._currentIndex = max(self._currentIndex-1,0)
self._highlighted = self._currentIndex
self._updateTabs()
def _andMoveToTheRight(self):
self._currentIndex = min(self._currentIndex+1,len(self._tabButtons)-1)
self._highlighted = self._currentIndex
self._updateTabs()
def wheelEvent(self, evt):
if evt.evt == TTkK.WHEEL_Up:
self._moveToTheLeft()
else:
self._andMoveToTheRight()
return True
def keyEvent(self, evt):
if evt.type == TTkK.SpecialKey:
if evt.key == TTkK.Key_Right:
self._highlighted = min(self._highlighted+1,len(self._tabButtons)-1)
self._updateTabs()
return True
elif evt.key == TTkK.Key_Left:
self._highlighted = max(self._highlighted-1,0)
self._updateTabs()
return True
if ( evt.type == TTkK.Character and evt.key==" " ) or \
( evt.type == TTkK.SpecialKey and evt.key == TTkK.Key_Enter ):
self._currentIndex = self._highlighted
self._updateTabs()
return True
return False
def paintEvent(self, canvas):
style = self.currentStyle()
borderColor = style['borderColor']
w = self.width()
tt = TTkCfg.theme.tab
if self._small:
lse = tt[23] if self._sideEnd & TTkK.LEFT else tt[19]
rse = tt[24] if self._sideEnd & TTkK.RIGHT else tt[19]
canvas.drawText(pos=(0,1),text=lse + tt[19]*(w-2) + rse, color=borderColor)
else:
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)
'''
┌────────────────────────────┐
│ Root Layout │
│┌────────┬────────┬────────┐│
││ Left M │ TABS │ RightM ││
│└────────┴────────┴────────┘│
│┌──────────────────────────┐│
││ Layout ││
││ ││
│└──────────────────────────┘│
└────────────────────────────┘
╭─┌──┌──────╔══════╗──────┬──────┐─╮
┌[M1]┬[M2]┤◀│La│Label1║Label2║Label3│Label4│▶│
╞════╧════╧═══════════╩══════╩═══════════════╡
leftscroller rightScroller
'''