Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dispose widget #217

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions TermTk/TTkCore/shortcut.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,14 @@ def __init__(self,
TTkShortcut._shortcuts[key] = []
TTkShortcut._shortcuts[key].append(self)

def dispose(self):
self.activated.clear()
if self._key in TTkShortcut._shortcuts:
if self in TTkShortcut._shortcuts[self._key]:
TTkShortcut._shortcuts[self._key].remove(self)
if not TTkShortcut._shortcuts[self._key]:
del TTkShortcut._shortcuts[self._key]

@staticmethod
def processKey(key, focusWidget):
# TTkLog.debug(f"{str(key)=}")
Expand Down
14 changes: 9 additions & 5 deletions TermTk/TTkCore/signal.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,14 +65,14 @@ def pyTTkSlot(*args, **kwargs):
def pyTTkSlot_d(func):
# Add signature attributes to the function
func._TTkslot_attr = args
func._TTkslot_sigList = []
return func
return pyTTkSlot_d

def pyTTkSignal(*args, **kwargs):
return _pyTTkSignal_obj(*args, **kwargs)

class _pyTTkSignal_obj():
_signals = []
__slots__ = ('_types', '_name', '_revision', '_connected_slots', '_mutex')
def __init__(self, *args, **kwargs):
# ref: http://pyqt.sourceforge.net/Docs/PyQt5/signals_slots.html#PyQt5.QtCore.pyqtSignal
Expand All @@ -92,7 +92,6 @@ def __init__(self, *args, **kwargs):
self._revision = kwargs.get('revision', 0)
self._connected_slots = {}
self._mutex = Lock()
_pyTTkSignal_obj._signals.append(self)

def connect(self, slot):
# ref: http://pyqt.sourceforge.net/Docs/PyQt5/signals_slots.html#connect
Expand Down Expand Up @@ -126,13 +125,19 @@ def connect(self, slot):
if not issubclass(a,b):
error = "Decorated slot has no signature compatible: "+slot.__name__+str(slot._TTkslot_attr)+" != signal"+str(self._types)
raise TypeError(error)
if hasattr(slot, '_TTkslot_sigList'):
if self not in slot._TTkslot_sigList:
slot._TTkslot_sigList.append(self)
if slot not in self._connected_slots:
self._connected_slots[slot]=slice(nargs)

def disconnect(self, *args, **kwargs):
for slot in args:
if slot in self._connected_slots:
del self._connected_slots[slot]
if hasattr(slot, '_TTkslot_sigList'):
if self in slot._TTkslot_sigList:
slot._TTkslot_sigList.remove(self)

def emit(self, *args, **kwargs):
if not self._mutex.acquire(False): return
Expand All @@ -147,9 +152,8 @@ def clear(self):
self._connected_slots = {}

@staticmethod
def clearAll():
for s in _pyTTkSignal_obj._signals:
s.clear()
def clearAll(self):
pass

def forward(self):
def _ret(*args, **kwargs):
Expand Down
1 change: 1 addition & 0 deletions TermTk/TTkCore/ttk.py
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,7 @@ def _quit(self):
'''Tells the application to exit with a return code.'''
if self._timer:
self._timer.timeout.disconnect(self._time_event)
self.dispose(children=True)
TTkInput.inputEvent.clear()
self._paintEvent.set()
TTkInput.close()
Expand Down
8 changes: 8 additions & 0 deletions TermTk/TTkWidgets/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,14 @@ def __init__(self, *, padding=(0,0,0,0), forwardStyle=False,**kwargs):
self._layout.setParent(self)
self.update(updateLayout=True)

def dispose(self, children:bool=False):
super().dispose()
if children:
cl = [_w for _w in self._layout.iterWidgets(onlyVisible=False, recurse=True)]
for wid in reversed(cl):
wid.dispose()
TTkLog.debug(wid._name)

def addWidget(self, widget):
'''
.. warning::
Expand Down
9 changes: 9 additions & 0 deletions TermTk/TTkWidgets/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,15 @@ def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setBorder(self._border)

def dispose(self):
if self._menubarTop:
self._menubarTop.dispose()
if self._menubarBottom:
self._menubarBottom.dispose()
self._menubarTop = None
self._menubarBottom = None
super().dispose()

def newMenubarTop(self):
'''newMenubarTop

Expand Down
10 changes: 9 additions & 1 deletion TermTk/TTkWidgets/menubar.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,10 @@ def paintEvent(self, canvas):

class TTkMenuBarLayout(TTkHBoxLayout):
'''TTkMenuBarLayout'''
__slots__ = ('_itemsLeft', '_itemsCenter', '_itemsRight', '_buttons')
__slots__ = ('_itemsLeft', '_itemsCenter', '_itemsRight', '_buttons', '_shortcuts')
def __init__(self, *args, **kwargs):
self._buttons = []
self._shortcuts = []
TTkHBoxLayout.__init__(self, *args, **kwargs)
self._itemsLeft = TTkHBoxLayout()
self._itemsCenter = TTkHBoxLayout()
Expand All @@ -101,6 +102,7 @@ def addMenu(self,text:TTkString, data:object=None, checkable:bool=False, checked
for ch in shortcuts:
shortcut = TTkShortcut(key=TTkK.ALT | ord(ch.upper()))
shortcut.activated.connect(button.shortcutEvent)
self._shortcuts.append(shortcut)
self._mbItems(alignment).addWidget(button)
self._buttons.append(button)
self.update()
Expand All @@ -121,3 +123,9 @@ def clear(self):
self._itemsLeft.removeItems(self._itemsLeft.children())
self._itemsCenter.removeItems(self._itemsCenter.children())
self._itemsRight.removeItems(self._itemsRight.children())

def dispose(self):
for sc in self._shortcuts:
sc.dispose()
self._shortcuts = []

22 changes: 20 additions & 2 deletions TermTk/TTkWidgets/widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@

__all__ = ['TTkWidget']

import types

from TermTk.TTkCore.cfg import TTkCfg, TTkGlbl
from TermTk.TTkCore.constant import TTkK
from TermTk.TTkCore.log import TTkLog
Expand Down Expand Up @@ -168,7 +170,7 @@ def __init__(self, *args, **kwargs):

def __del__(self):
''' .. caution:: Don't touch this! '''
# TTkLog.debug("DESTRUCTOR")
# TTkLog.debug(f"DESTRUCTOR -> {self._name}")

# clean all the signals, slots
#for an in dir(self):
Expand Down Expand Up @@ -465,14 +467,30 @@ def lowerWidget(self):
@pyTTkSlot()
def close(self):
'''close'''
self.dispose()
self.closed.emit(self)

def dispose(self):
'''dispose'''
refSig = type(pyTTkSignal())
for p in dir(self):
if type(pr:=getattr(self,p)) != types.MethodType:
continue
if hasattr(pr, '_TTkslot_sigList'):
for sig in pr._TTkslot_sigList.copy():
sig.disconnect(pr)
if type(pr) is refSig:
pr.clear()
if _p := self._parent:
if _rl := _p.rootLayout():
_rl.removeWidget(self)
_p.update()
TTkHelper.removeOverlayAndChild(self)
self._parent = None
self.hide()
self.closed.emit(self)
# self._widgetItem._widget = None
# self._widgetItem = None
# self._canvas = None

@pyTTkSlot(bool)
def setVisible(self, visible: bool):
Expand Down
2 changes: 1 addition & 1 deletion tests/t.ui/test.ui.016.about.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,6 @@

root = ttk.TTk()

win = ttk.TTkAbout(parent=root, pos=(1,1))
ttk.TTkAbout(parent=root, pos=(1,1))

root.mainloop()
94 changes: 94 additions & 0 deletions tests/weakref/test.06.gc.01.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
#!/usr/bin/env python3

# MIT License
#
# Copyright (c) 2023 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.

# Example inspired by
# https://stackoverflow.com/questions/39838793/python-object-is-being-referenced-by-an-object-i-cannot-find

import gc, weakref, time
import os,sys

sys.path.append(os.path.join(sys.path[0],'../..'))
sys.path.append(os.path.join(sys.path[0],'.'))
import TermTk as ttk

ttk.TTkLog.use_default_stdout_logging()

class testClass():
pass

def pobjs():
for i,o in enumerate(gc.get_objects()[-100:]):
ss = str(o)
if "Foo" in ss:
print(f" * {i} - {ss}")

def _ref(o,ch="*"):
# print(f"\n### -> Referents - {o}")
# for i,r in enumerate(gc.get_referents(o)):
# print(f" - {i} ) {r}")
print(f"\n### -> Referrers - {o}")
for i,r in enumerate(gc.get_referrers(o)):
print(f" {ch} {i} ) ({type(r)})-> {r}")
print("")

v1 = {'b':2345}

print(f"\nStart {gc.isenabled()=}")
# print(f"{gc.set_debug(gc.DEBUG_LEAK)=}")

def _gccb(phase,info):
print(f" ---> {gc.garbage=}")
print(f" ---> {phase=} {info=}")

# gc.callbacks.append(_gccb)

print("\n############# Phase 1 ##################")
foo = ttk.TTkAbout()
bar1 = ttk.TTkButton()
bar2 = ttk.TTkWidget()
pep = testClass()

ttk.TTkHelper._updateWidget.clear()
ttk.TTkHelper._updateBuffer.clear()

print(f"{gc.collect()=}")
print(f"Mid {gc.get_count()=}")

_ref(foo)
_ref(foo)
_ref(foo, "-Active-")

foo.close()
ttk.TTkHelper._updateWidget.clear()
ttk.TTkHelper._updateBuffer.clear()

_ref(foo, "-Closed-")
del foo
# _ref(bar1)
# _ref(pep)

print(f"{gc.collect()=}")
print(f"End {gc.get_count()=}")
# time.sleep(3)

97 changes: 97 additions & 0 deletions tests/weakref/test.06.gc.02.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
#!/usr/bin/env python3

# MIT License
#
# Copyright (c) 2023 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.

# Example inspired by
# https://stackoverflow.com/questions/39838793/python-object-is-being-referenced-by-an-object-i-cannot-find

import gc, weakref, time
import os,sys

sys.path.append(os.path.join(sys.path[0],'../..'))
sys.path.append(os.path.join(sys.path[0],'.'))
import TermTk as ttk

# ttk.TTkLog.use_default_stdout_logging()

class testClass():
pass

def pobjs():
for i,o in enumerate(gc.get_objects()[-100:]):
ss = str(o)
if "Foo" in ss:
ttk.TTkLog.info(f" * {i} - {ss}")

def _ref(o,ch="*"):
# ttk.TTkLog.info(f"\n### -> Referents - {o}")
# for i,r in enumerate(gc.get_referents(o)):
# ttk.TTkLog.info(f" - {i} ) {r}")
ttk.TTkLog.info(f"### -> Referrers - {o}")
for i,r in enumerate(gc.get_referrers(o)):
ttk.TTkLog.info(f" {ch} {i} ) ({type(r)})-> {r}")
ttk.TTkLog.info("")

def _gccb(phase,info):
ttk.TTkLog.info(f" ---> {gc.garbage=}")
ttk.TTkLog.info(f" ---> {phase=} {info=}")

class Button2(ttk.TTkButton):pass

root = ttk.TTk()
ttk.TTkLogViewer(parent=root, pos=(20,0), size=(150,30))

ttk.TTkLog.info(f"Start {gc.isenabled()=}")
# ttk.TTkLog.info(f"{gc.set_debug(gc.DEBUG_LEAK)=}")

# gc.callbacks.append(_gccb)

ttk.TTkLog.info("############# Phase 1 ##################")

foo = ttk.TTkAbout(parent=root)

bar1 = Button2(parent=root, border=True, text="Do it")
bar2 = ttk.TTkWidget()
pep = testClass()

ttk.TTkLog.info(f"{gc.collect()=}")
ttk.TTkLog.info(f"Mid {gc.get_count()=}")


@ttk.pyTTkSlot()
def _doit():
ttk.TTkLog.info(f"{gc.collect()=}")
ttk.TTkLog.info(f"End {gc.get_count()=}")
bar1.clicked.connect(_doit)
bar1.clicked.connect(foo.close)

foo.closed.connect(lambda _x: _ref(_x, "-Closed-"))

_ref(foo, "-Active-")
del foo

root.mainloop()

foo.close()

_ref(foo, "-Closed-")
Loading
Loading