33
44from __future__ import annotations
55
6- import weakref
76from typing import TYPE_CHECKING , Any , Callable
87
98import numpy as np
2827from plotpy .interfaces import ICurveItemType
2928from plotpy .items import Marker , XRangeSelection , YRangeSelection
3029from plotpy .items .curve .base import CurveItem
31- from plotpy .tools .base import DefaultToolbarID , InteractiveTool , ToggleTool
30+ from plotpy .tools .base import (
31+ DefaultToolbarID ,
32+ InteractiveTool ,
33+ LastItemHolder ,
34+ ToggleTool ,
35+ )
3236from plotpy .tools .cursor import BaseCursorTool
3337
3438if TYPE_CHECKING :
35-
3639 from plotpy .items .label import DataInfoLabel
3740 from plotpy .plot .base import BasePlot
3841 from plotpy .plot .manager import PlotManager
@@ -67,7 +70,7 @@ def __init__(
6770 tip : str | None = None ,
6871 ) -> None :
6972 super ().__init__ (manager , toolbar_id , title = title , icon = icon , tip = tip )
70- self ._last_item : weakref . ReferenceType [ CurveItem ] | None = None
73+ self .last_item_holder = LastItemHolder ( ICurveItemType )
7174 self .label : DataInfoLabel | None = None
7275 self .labelfuncs = labelfuncs or self .LABELFUNCS
7376
@@ -173,34 +176,14 @@ def set_labelfuncs(
173176 """
174177 self .labelfuncs = labelfuncs
175178
176- def get_last_item (self ) -> CurveItem | None :
177- """Get last item on which the tool was used"""
178- if self ._last_item is not None :
179- return self ._last_item ()
180- return None
181-
182- def get_associated_item (self , plot : BasePlot ) -> CurveItem | None :
183- """Get associated item
184-
185- Args:
186- plot: BasePlot instance
187-
188- Returns:
189- curve item or None
190- """
191- items = plot .get_selected_items (item_type = ICurveItemType )
192- if len (items ) == 1 :
193- self ._last_item = weakref .ref (items [0 ])
194- return self .get_last_item ()
195-
196179 def get_label_title (self ) -> str | None :
197180 """Return label title"""
198- curve = self .get_associated_item ( self . manager . get_plot () )
181+ curve = self .last_item_holder . get ( )
199182 return curve .title ().text () if curve else None
200183
201184 def get_computation_specs (self ) -> list [tuple [CurveItem , str , Callable [..., Any ]]]:
202185 """Return computation specs"""
203- curve = self .get_associated_item ( self . manager . get_plot () )
186+ curve = self .last_item_holder . get ( )
204187 return [(curve , label , func ) for label , func in self .labelfuncs ]
205188
206189 def update_status (self , plot : BasePlot ) -> None :
@@ -209,7 +192,7 @@ def update_status(self, plot: BasePlot) -> None:
209192 Args:
210193 plot: BasePlot instance
211194 """
212- item = self .get_associated_item (plot )
195+ item = self .last_item_holder . update_from_selection (plot )
213196 self .action .setEnabled (item is not None )
214197
215198
0 commit comments