Browse Source

chore: improve typing (#417)

pull/423/head
Pier CeccoPierangioliEugenio 9 months ago committed by GitHub
parent
commit
833005acd1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
  1. 2
      apps/perspectivator/perspectivator.wand.py
  2. 4
      libs/pyTermTk/TermTk/TTkCore/constant.py
  3. 49
      libs/pyTermTk/TermTk/TTkCore/string.py
  4. 8
      libs/pyTermTk/TermTk/TTkWidgets/container.py
  5. 87
      libs/pyTermTk/TermTk/TTkWidgets/widget.py
  6. 6
      tools/check.import.sh
  7. 1
      tools/image/example.projection.2.py

2
apps/perspectivator/perspectivator.wand.py

@ -26,6 +26,8 @@ import argparse
from dataclasses import dataclass from dataclasses import dataclass
from typing import Optional,Tuple,List,Dict from typing import Optional,Tuple,List,Dict
from PIL import ImageDraw, ImageFilter
import numpy as np import numpy as np
from wand.image import Image from wand.image import Image

4
libs/pyTermTk/TermTk/TTkCore/constant.py

@ -22,6 +22,8 @@
__all__ = ['TTkConstant', 'TTkK'] __all__ = ['TTkConstant', 'TTkK']
from enum import IntEnum
class TTkConstant: class TTkConstant:
'''Class container of all the constants used in :mod:`~TermTk`''' '''Class container of all the constants used in :mod:`~TermTk`'''
@ -56,7 +58,7 @@ class TTkConstant:
ColorModifier = 0x08 ColorModifier = 0x08
'''The :py:class:`TTkColor` include a color modifier based on :py:class:`TTkColorModifier`''' '''The :py:class:`TTkColor` include a color modifier based on :py:class:`TTkColorModifier`'''
class FocusPolicy(int): class FocusPolicy(IntEnum):
''' '''
This Class type defines the various policies a widget This Class type defines the various policies a widget
can have with respect to acquiring keyboard focus. can have with respect to acquiring keyboard focus.

49
libs/pyTermTk/TermTk/TTkCore/string.py

@ -20,18 +20,15 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE. # SOFTWARE.
from __future__ import annotations
__all__ = ['TTkString'] __all__ = ['TTkString']
import os import os
import re import re
import unicodedata import unicodedata
from types import GeneratorType from types import GeneratorType
from typing import Any from typing import Any, Optional, Union, List, Tuple
try:
from typing import Self
except:
class Self(): pass
from TermTk.TTkCore.cfg import TTkCfg from TermTk.TTkCore.cfg import TTkCfg
from TermTk.TTkCore.constant import TTkK from TermTk.TTkCore.constant import TTkK
@ -69,11 +66,13 @@ class TTkString():
unicodeWideOverflowColor = TTkColor.fg("#888888")+TTkColor.bg("#000088") unicodeWideOverflowColor = TTkColor.fg("#888888")+TTkColor.bg("#000088")
__slots__ = ('_text','_colors','_baseColor','_hasTab','_hasSpecialWidth') __slots__ = ('_text','_colors','_baseColor','_hasTab','_hasSpecialWidth')
_text:str
_colors:List[TTkColor]
_baseColor:TTkColor
def __init__(self, def __init__(self,
text:str="", text:Union[str,TTkString]="",
color:TTkColor=None) -> None: color:Optional[TTkColor]=None) -> None:
if issubclass(type(text), TTkString): if isinstance(text, TTkString):
self._text = text._text self._text = text._text
self._colors = text._colors if color is None else [color]*len(self._text) self._colors = text._colors if color is None else [color]*len(self._text)
self._baseColor = text._baseColor self._baseColor = text._baseColor
@ -120,7 +119,7 @@ class TTkString():
def __str__(self) -> str: def __str__(self) -> str:
return self._text return self._text
def __add__(self, other:Self) -> Self: def __add__(self, other:TTkString) -> TTkString:
ret = TTkString() ret = TTkString()
ret._baseColor = self._baseColor ret._baseColor = self._baseColor
if isinstance(other, TTkString): if isinstance(other, TTkString):
@ -142,7 +141,7 @@ class TTkString():
ret._baseColor = other ret._baseColor = other
return ret return ret
def __radd__(self, other:Self) -> Self: def __radd__(self, other:TTkString) -> TTkString:
ret = TTkString() ret = TTkString()
ret._baseColor = self._baseColor ret._baseColor = self._baseColor
if isinstance(other, TTkString): if isinstance(other, TTkString):
@ -180,7 +179,7 @@ class TTkString():
def __gt__(self, other): return self._text > other._text if issubclass(type(other),TTkString) else self._text > other def __gt__(self, other): return self._text > other._text if issubclass(type(other),TTkString) else self._text > other
def __ge__(self, other): return self._text >= other._text if issubclass(type(other),TTkString) else self._text >= other def __ge__(self, other): return self._text >= other._text if issubclass(type(other),TTkString) else self._text >= other
def sameAs(self, other:Self) -> bool: def sameAs(self, other:TTkString) -> bool:
if not issubclass(type(other),TTkString): return False if not issubclass(type(other),TTkString): return False
return ( return (
self==other and self==other and
@ -190,7 +189,7 @@ class TTkString():
def isdigit(self) -> bool: def isdigit(self) -> bool:
return self._text.isdigit() return self._text.isdigit()
def lstrip(self, ch:str) -> Self: def lstrip(self, ch:str) -> TTkString:
ret = TTkString() ret = TTkString()
ret._text = self._text.lstrip(ch) ret._text = self._text.lstrip(ch)
ret._colors = self._colors[-len(ret._text):] ret._colors = self._colors[-len(ret._text):]
@ -199,7 +198,7 @@ class TTkString():
def charAt(self, pos:int) -> str: def charAt(self, pos:int) -> str:
return self._text[pos] return self._text[pos]
def setCharAt(self, pos:int, char:str) -> Self: def setCharAt(self, pos:int, char:str) -> TTkString:
self._text = self._text[:pos]+char+self._text[pos+1:] self._text = self._text[:pos]+char+self._text[pos+1:]
self._checkWidth() self._checkWidth()
return self return self
@ -209,11 +208,11 @@ class TTkString():
return TTkColor() return TTkColor()
return self._colors[pos] return self._colors[pos]
def setColorAt(self, pos, color) -> Self: def setColorAt(self, pos, color) -> TTkString:
self._colors[pos] = color self._colors[pos] = color
return self return self
def tab2spaces(self, tabSpaces=4) -> Self: def tab2spaces(self, tabSpaces=4) -> TTkString:
'''Return the string representation with the tabs (converted in spaces) trimmed and aligned''' '''Return the string representation with the tabs (converted in spaces) trimmed and aligned'''
if not self._hasTab: return self if not self._hasTab: return self
ret = TTkString() ret = TTkString()
@ -327,7 +326,7 @@ class TTkString():
return out return out
return out+str(TTkColor.RST) return out+str(TTkColor.RST)
def align(self, width=None, color=TTkColor.RST, alignment=TTkK.NONE) -> Self: def align(self, width=None, color=TTkColor.RST, alignment=TTkK.NONE) -> TTkString:
''' Align the string ''' Align the string
:param width: the new width :param width: the new width
@ -389,7 +388,7 @@ class TTkString():
return ret return ret
def extractShortcuts(self) -> Self: def extractShortcuts(self) -> Tuple[TTkString,List[str]]:
def _chGenerator(): def _chGenerator():
for ch,color in zip(self._text,self._colors): for ch,color in zip(self._text,self._colors):
yield ch,color yield ch,color
@ -406,7 +405,7 @@ class TTkString():
_newColors.append(color) _newColors.append(color)
return TTkString._importString1(_newText,_newColors), _ret return TTkString._importString1(_newText,_newColors), _ret
def replace(self, *args, **kwargs) -> Self: def replace(self, *args, **kwargs) -> TTkString:
''' **replace** (*old*, *new*, *count*) ''' **replace** (*old*, *new*, *count*)
Replace "**old**" match with "**new**" string for "**count**" times Replace "**old**" match with "**new**" string for "**count**" times
@ -454,7 +453,7 @@ class TTkString():
return ret return ret
def completeColor(self, color:TTkColor, match=None, posFrom=None, posTo=None) -> Self: def completeColor(self, color:TTkColor, match=None, posFrom=None, posTo=None) -> TTkString:
''' Complete the color of the entire string or a slice of it ''' Complete the color of the entire string or a slice of it
The Fg and/or Bg of the string is replaced with the selected Fg/Bg color only if missing The Fg and/or Bg of the string is replaced with the selected Fg/Bg color only if missing
@ -495,7 +494,7 @@ class TTkString():
return ret return ret
def setColor(self, color, match=None, posFrom=None, posTo=None) -> Self: def setColor(self, color, match=None, posFrom=None, posTo=None) -> TTkString:
''' Set the color of the entire string or a slice of it ''' Set the color of the entire string or a slice of it
If only the color is specified, the entire string is colorized If only the color is specified, the entire string is colorized
@ -531,7 +530,7 @@ class TTkString():
ret._colors += self._colors ret._colors += self._colors
return ret return ret
def substring(self, fr=None, to=None) -> Self: def substring(self, fr=None, to=None) -> TTkString:
''' Return the substring ''' Return the substring
:param fr: the starting of the slice, defaults to 0 :param fr: the starting of the slice, defaults to 0
@ -546,7 +545,7 @@ class TTkString():
ret._fastCheckWidth(self._hasSpecialWidth) ret._fastCheckWidth(self._hasSpecialWidth)
return ret return ret
def split(self, separator ) -> list[Self]: def split(self, separator ) -> list[TTkString]:
''' Split the string using a separator ''' Split the string using a separator
.. note:: Only a one char separator is currently supported .. note:: Only a one char separator is currently supported
@ -599,7 +598,7 @@ class TTkString():
def getIndexes(self, char): def getIndexes(self, char):
return [i for i,c in enumerate(self._text) if c==char] return [i for i,c in enumerate(self._text) if c==char]
def join(self, strings:list[Self]) -> Self: def join(self, strings:list[TTkString]) -> TTkString:
''' Join the input strings using the current as separator ''' Join the input strings using the current as separator
:param strings: the list of strings to be joined :param strings: the list of strings to be joined

8
libs/pyTermTk/TermTk/TTkWidgets/container.py

@ -22,7 +22,7 @@
__all__ = ['TTkContainer', 'TTkPadding'] __all__ = ['TTkContainer', 'TTkPadding']
from typing import NamedTuple from typing import NamedTuple, Optional
from TermTk.TTkCore.constant import TTkK from TermTk.TTkCore.constant import TTkK
from TermTk.TTkCore.log import TTkLog from TermTk.TTkCore.log import TTkLog
@ -104,8 +104,8 @@ class TTkContainer(TTkWidget):
'_layout') '_layout')
def __init__(self, *, def __init__(self, *,
layout:TTkLayout=None, layout:Optional[TTkLayout]=None,
padding:TTkPadding = None, padding:Optional[TTkPadding] = None,
paddingTop:int = 0, paddingTop:int = 0,
paddingBottom:int = 0, paddingBottom:int = 0,
paddingLeft:int = 0, paddingLeft:int = 0,
@ -381,7 +381,7 @@ class TTkContainer(TTkWidget):
self._height - self._padt - self._padb) self._height - self._padt - self._padb)
self.rootLayout().update() self.rootLayout().update()
def getWidgetByName(self, name: str) -> TTkWidget: def getWidgetByName(self, name: str) -> Optional[TTkWidget]:
''' '''
Return the widget from its name. Return the widget from its name.

87
libs/pyTermTk/TermTk/TTkWidgets/widget.py

@ -20,14 +20,11 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE. # SOFTWARE.
__all__ = ['TTkWidget'] from __future__ import annotations
from typing import Callable, Any, List __all__ = ['TTkWidget']
try: from typing import ( TYPE_CHECKING, Callable, Any, List, Optional, Tuple, Union, Dict )
from typing import Self
except:
class Self(): pass
from TermTk.TTkCore.cfg import TTkCfg, TTkGlbl from TermTk.TTkCore.cfg import TTkCfg, TTkGlbl
from TermTk.TTkCore.constant import TTkK from TermTk.TTkCore.constant import TTkK
@ -43,6 +40,9 @@ from TermTk.TTkTemplates.keyevents import TKeyEvents
from TermTk.TTkLayouts.layout import TTkWidgetItem from TermTk.TTkLayouts.layout import TTkWidgetItem
from TermTk.TTkCore.TTkTerm.inputmouse import TTkMouseEvent from TermTk.TTkCore.TTkTerm.inputmouse import TTkMouseEvent
if TYPE_CHECKING:
from TermTk import TTkContainer
class TTkWidget(TMouseEvents,TKeyEvents, TDragEvents): class TTkWidget(TMouseEvents,TKeyEvents, TDragEvents):
''' Widget sizes: ''' Widget sizes:
@ -122,25 +122,51 @@ class TTkWidget(TMouseEvents,TKeyEvents, TDragEvents):
#Signals #Signals
'focusChanged', 'sizeChanged', 'currentStyleChanged', 'closed') 'focusChanged', 'sizeChanged', 'currentStyleChanged', 'closed')
def __init__(self, _name:str
parent:Self = None, _parent:Optional[TTkContainer]
x:int=0, y:int=0, _x:int
width:int=0, height:int=0, _y:int
pos : tuple = None, _width:int
size : tuple = None, _height:int
maxSize : tuple = None, _maxw:int
maxWidth : int = 0x10000, _maxh:int
maxHeight: int = 0x10000, _minw:int
minSize : tuple = None, _minh:int
minWidth : int = 0x00000, _focus:bool
minHeight: int = 0x00000, _focus_policy:TTkK.FocusPolicy
name : str = None, _canvas:TTkCanvas
visible : bool = True, _widgetItem:TTkWidgetItem
enabled : bool = True, _visible:bool
toolTip : TTkString = '', _pendingMouseRelease:bool
style : dict = None, _enabled:bool
addStyle : dict = None, _style:Dict
**kwargs) -> None: _currentStyle:Dict
_toolTip:TTkString
_dropEventProxy:Any
_widgetCursor:Tuple[int,int]
_widgetCursorEnabled:bool
_widgetCursorType:int
def __init__(
self,
parent:Optional[TTkContainer] = None,
x:int=0, y:int=0,
width:int=0, height:int=0,
pos : Optional[Tuple[int,int]] = None,
size : Optional[Tuple[int,int]] = None,
maxSize : Optional[Tuple[int,int]] = None,
maxWidth : int = 0x10000,
maxHeight: int = 0x10000,
minSize : Optional[Tuple[int,int]] = None,
minWidth : int = 0x00000,
minHeight: int = 0x00000,
name : Optional[str] = None,
visible : bool = True,
enabled : bool = True,
toolTip : Union[TTkString,str] = '',
style : Optional[Dict] = None,
addStyle : Optional[Dict] = None,
**kwargs) -> None:
''' '''
:param name: the name of the widget, defaults to "" :param name: the name of the widget, defaults to ""
:type name: str, optional :type name: str, optional
@ -401,7 +427,7 @@ class TTkWidget(TMouseEvents,TKeyEvents, TDragEvents):
:param txt: the paste object :param txt: the paste object
:type txt: str :type txt: str
''' '''
return False pass
def _mouseEventParseChildren(self, evt:TTkMouseEvent) -> bool: def _mouseEventParseChildren(self, evt:TTkMouseEvent) -> bool:
return False return False
@ -813,14 +839,15 @@ class TTkWidget(TMouseEvents,TKeyEvents, TDragEvents):
_S_PRESSED = 0x20 _S_PRESSED = 0x20
_S_RELEASED = 0x40 _S_RELEASED = 0x40
def style(self) -> dict: def style(self) -> Dict:
return self._style.copy() return self._style.copy()
def currentStyle(self) -> dict: def currentStyle(self) -> Dict:
return self._currentStyle return self._currentStyle
def setCurrentStyle(self, style) -> dict: def setCurrentStyle(self, style) -> None:
if style == self._currentStyle: return if style == self._currentStyle:
return
self._currentStyle = style self._currentStyle = style
self.currentStyleChanged.emit(style) self.currentStyleChanged.emit(style)
self.update() self.update()

6
tools/check.import.sh

@ -8,6 +8,7 @@ __check(){
grep -v -e "import re" -e "import os" -e "import datetime" | grep -v -e "import re" -e "import os" -e "import datetime" |
grep -v \ grep -v \
-e "from dataclasses" \ -e "from dataclasses" \
-e "from __future__ import annotations" \
-e "signal.py:from inspect import getfullargspec" \ -e "signal.py:from inspect import getfullargspec" \
-e "signal.py:from types import LambdaType" \ -e "signal.py:from types import LambdaType" \
-e "signal.py:from threading import Lock" \ -e "signal.py:from threading import Lock" \
@ -41,8 +42,8 @@ __check(){
-e "propertyanimation.py:from types import LambdaType" \ -e "propertyanimation.py:from types import LambdaType" \
-e "propertyanimation.py:import time, math" \ -e "propertyanimation.py:import time, math" \
-e "savetools.py:import importlib.util" \ -e "savetools.py:import importlib.util" \
-e "savetools.py:import json" | -e "savetools.py:import json" \
-e "TTkCore/color.py:from __future__ import annotations" | -e "TTkCore/constant.py:from enum import IntEnum" |
grep -v \ grep -v \
-e "TTkTerm/input_mono.py:from time import time" \ -e "TTkTerm/input_mono.py:from time import time" \
-e "TTkTerm/input_mono.py:import platform" \ -e "TTkTerm/input_mono.py:import platform" \
@ -109,6 +110,7 @@ __check(){
-e "TTkTerminal/__init__.py:import importlib.util" \ -e "TTkTerminal/__init__.py:import importlib.util" \
-e "TTkTerminal/__init__.py:import platform" | -e "TTkTerminal/__init__.py:import platform" |
grep -v \ grep -v \
-e "TTkWidgets/widget.py:from __future__ import annotations" \
-e "TTkWidgets/tabwidget.py:from enum import Enum" \ -e "TTkWidgets/tabwidget.py:from enum import Enum" \
-e "TTkModelView/__init__.py:from importlib.util import find_spec" \ -e "TTkModelView/__init__.py:from importlib.util import find_spec" \
-e "TTkModelView/tablemodelcsv.py:import csv" \ -e "TTkModelView/tablemodelcsv.py:import csv" \

1
tools/image/example.projection.2.py

@ -1,4 +1,5 @@
import math import math
import numpy as np,array
def project_3d_to_2d(square_3d, observer, look_at, fov=90, aspect_ratio=1, near=0.1, far=1000): def project_3d_to_2d(square_3d, observer, look_at, fov=90, aspect_ratio=1, near=0.1, far=1000):
""" """

Loading…
Cancel
Save