a
    §ˆc¨m  ã                   @   sÄ   d Z ddlmZ ddlmZ ddlmZmZmZm	Z	m
Z
mZmZmZmZmZmZmZmZmZmZmZ ddlmZmZmZ ddlmZ ddlmZ dd	lmZ dd
l m!Z! eeƒZ"G dd„ de	ƒZ#dS )z‚ Defines the abstract Editor class, which represents an editing control for
    an object trait in a Traits-based user interface.
é    )Úcontextmanager)Úpartial)ÚAnyÚBoolÚCallableÚHasPrivateTraitsÚ	HasTraitsÚInstanceÚListÚPropertyÚReadOnlyÚSetÚStrÚ
TraitErrorÚTraitListEventÚTupleÚ	UndefinedÚcached_property)Únot_noneÚxgetattrÚxsetattré   )ÚEditorFactory)ÚContextValue©ÚUndoItem)ÚItemc                       s  e Zd ZdZeddd�ZedƒZeedd�Z	e
ƒ Zeƒ Zeƒ Zedd�Ze
ƒ Zeeddd�Zedd�Zedd�ZedƒZedƒZedƒZeedd�ZedƒZeƒ Zeƒ Zeƒ ZedƒZ e!eƒZ"e#e$eee%ƒƒZ&e#e$ee%ƒƒZ'dd	„ Z(d
d„ Z)dd„ Z*dd„ Z+dd„ Z,dJdd„Z-dd„ Z.dd„ Z/dd„ Z0dd„ Z1dd„ Z2dd „ Z3dKd"d#„Z4d$d%„ Z5dLd&d'„Z6d(d)„ Z7d*d+„ Z8e9d,d-„ ƒZ:e9d.d/„ ƒZ;e9d0d1„ ƒZ<‡ fd2d3„Z=d4d5„ Z>d6d7„ Z?d8d9„ Z@d:d;„ ZAd<d=„ ZBeCd>d?„ ƒZDeCd@dA„ ƒZEdBdC„ ZFdDdE„ ZGdFdG„ ZHdHdI„ ZI‡  ZJS )MÚEditorz\Represents an editing control for an object trait in a Traits-based
    user interface.
    ztraitsui.ui.UIT©Zclean_upÚobject© Fc                 C   s   t dƒ‚dS )aw  Create and initialize the underlying toolkit widget.

        This method must be overriden by subclasses.  Implementations must
        ensure that the :attr:`control` trait is set to an appropriate
        toolkit object.

        Parameters
        ----------
        parent : toolkit control
            The parent toolkit object of the editor's toolkit objects.
        úThis method must be overriden.N©ÚNotImplementedError)ÚselfÚparentr    r    úR/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.9/site-packages/traitsui/editor.pyÚinit‡   s    zEditor.initc                 C   s   dS )z‡Updates the editor when the value changes externally to the editor.

        This should normally be overridden in a subclass.
        Nr    ©r$   r    r    r&   Úupdate_editor•   s    zEditor.update_editorc                 C   s.   ddl m} ||  ¡ | jd t|ƒdd� dS )z·Handles an error that occurs while setting the object's trait value.

        Parameters
        ----------
        excp : Exception
            The exception which occurred.
        r   )Úinformationz value errorÚplain)r%   ÚtitleÚmessageZtext_formatN)Z
pyface.apir*   Úget_control_widgetÚdescriptionÚstr)r$   Úexcpr*   r    r    r&   Úerrorœ   s    üzEditor.errorc                 C   s   t dƒ‚dS )zwAssigns focus to the editor's underlying toolkit widget.

        This method must be overriden by subclasses.
        r!   Nr"   r(   r    r    r&   Ú	set_focus­   s    zEditor.set_focusc                 C   s   t dƒ‚dS )aD  Sets the tooltip for a toolkit control to the provided text.

        This method must be overriden by subclasses.

        Parameters
        ----------
        text : str
            The text to use for the tooltip.
        control : toolkit control
            The toolkit control that is having the tooltip set.
        r!   Nr"   ©r$   ÚcontrolÚtextr    r    r&   Úset_tooltip_text´   s    zEditor.set_tooltip_textNc                 C   s   | j  ||¡S )aŸ  Returns the text representation of a specified object trait value.

        This simply delegates to the factory's `string_value` method.
        Sub-classes may choose to override the default implementation.

        Parameters
        ----------
        value : any
            The value being edited.
        format_func : callable or None
            A function that takes a value and returns a string.
        )ÚfactoryÚstring_value)r$   ÚvalueZformat_funcr    r    r&   r9   Â   s    zEditor.string_valuec                 C   s   dS )a%  Restores saved user preference information for the editor.

        Editors with state may choose to override this. It will only be used
        if the editor has an `id` value.

        Parameters
        ----------
        prefs : dict
            A dictionary of preference values.
        Nr    )r$   Zprefsr    r    r&   Úrestore_prefsÑ   s    zEditor.restore_prefsc                 C   s   dS )aW  Returns any user preference information for the editor.

        Editors with state may choose to override this. It will only be used
        if the editor has an `id` value.

        Returns
        -------
        prefs : dict or None
            A dictionary of preference values, or None if no preferences to
            be saved.
        Nr    r(   r    r    r&   Ú
save_prefsÞ   s    zEditor.save_prefsc                 C   s@   | j }|dkr"| jj| j|dd� |  |¡ |  ¡  |  ¡  dS )zµFinish setting up the editor.

        Parameters
        ----------
        parent : toolkit control
            The parent toolkit object of the editor's toolkit objects.
        ÚNoneÚui)ÚdispatchN)Úextended_nameÚcontext_objectÚon_trait_changeÚ_update_editorr'   Ú_sync_valuesr)   )r$   r%   Únamer    r    r&   Úprepareî   s    ÿ
zEditor.preparec                 C   s”   | j du rdS | j}|dkr0| jj| j|dd� | jD ]\}}| j||dd� q6| jD ]\}}}|j||dd� qV| jdd�D ]}t| |dƒ q~dS )zïDisposes of the contents of an editor.

        This disconnects any synchronised values and resets references
        to other objects.

        Subclasses may chose to override this method to perform additional
        clean-up.
        Nr=   T©Úremover   )	r>   r@   rA   rB   rC   Ú
_user_fromÚ_user_toZtrait_namesÚsetattr)r$   rE   Úhandlerr   r    r    r&   Údisposeÿ   s    	
ÿzEditor.disposec                 G   sV   | j }|j}|dkrR|j}|durR||Ž }|durR||jkrH| |¡ n
| |¡ dS )a  Logs a change made in the editor with undo/redo history.

        Parameters
        ----------
        undo_factory : callable
            Callable that creates an undo item.  Often self.get_undo_item.
        *undo_args
            Any arguments to pass to the undo factory.
        r   N)r>   Z	_undoableÚhistoryÚnowÚaddÚextend)r$   Zundo_factoryZ	undo_argsr>   ZundoablerN   Úitemr    r    r&   Ú
log_change  s    

zEditor.log_changec                 C   s   t ||||d�S )a¬  Creates an undo history entry.

        Can be overridden in a subclass for special value types.

        Parameters
        ----------
        object : HasTraits instance
            The object being modified.
        name : str
            The name of the trait that is to be changed.
        old_value : any
            The original value of the trait.
        new_value : any
            The new value of the trait.
        )r   rE   Ú	old_valueÚ	new_valuer   ©r$   r   rE   rT   rU   r    r    r&   Úget_undo_item7  s    ÿzEditor.get_undo_itemÚbothc                 C   s0  |dkrdS d||f }|  d¡}t|ƒdkr:| j}|}	n*| jj|d  }d |dd… ¡}	|d }|dv rÀ|  |||	||¡ |sÀ|  ¡ �& t||	ƒ}
t	| ||
ƒ W d  ƒ n1 s¶0    Y  |d	v �r,|  
|||	||¡ |d
k�r,|�s,|  ¡ �& t| |ƒ}t||	|ƒ W d  ƒ n1 �s"0    Y  dS )ad  Synchronize an editor trait and a user object trait.

        Also sets the initial value of the editor trait from the
        user object trait (for modes 'from' and 'both'), and the initial
        value of the user object trait from the editor trait (for mode
        'to'), as long as the relevant traits are not events.

        Parameters
        ----------
        user_name : str
            The name of the trait to be used on the user object. If empty, no
            synchronization will be set up.
        editor_name : str
            The name of the relevant editor trait.
        mode : str, optional; one of 'to', 'from' or 'both'
            The direction of synchronization. 'from' means that trait changes
            in the user object should be propagated to the editor. 'to' means
            that trait changes in the editor should be propagated to the user
            object. 'both' means changes should be propagated in both
            directions. The default is 'both'.
        is_list : bool, optional
            If true, synchronization for item events will be set up in
            addition to the synchronization for the object itself.
            The default is False.
        is_event : bool, optional
            If true, this method won't attempt to initialize the user
            object or editor trait values. The default is False.
        Ú Nz%s:%sÚ.r   r   éÿÿÿÿ>   ÚfromrX   >   rX   Útor]   )ÚsplitÚlenrA   r>   ÚcontextÚjoinÚ
_bind_fromÚraise_to_debugr   rK   Ú_bind_tor   )r$   Z	user_nameÚeditor_nameÚmodeÚis_listZis_eventÚkeyÚpartsÚuser_objectÚ
xuser_nameZ
user_valueZeditor_valuer    r    r&   Ú
sync_valueM  s,    $


*


zEditor.sync_valuec                 C   s>   |  d¡\}}}|r"| jj| }n
|}| j}||tt||ƒfS )a±  Extract the object, name and a getter from an extended name

        Parameters
        ----------
        name : str
            The extended name to parse.

        Returns
        -------
        object, name, getter : any, str, callable
            The object from the context, the (extended) name of the
            attributes holding the value, and a callable which gets the
            current value from the context.
        rZ   )Ú	partitionr>   r`   rA   r   r   )r$   rE   Ú	base_nameÚ__r   r    r    r&   Úparse_extended_name“  s    zEditor.parse_extended_namec                 C   s2   |   ¡ }|du rdS |du r"| j}|  ||¡ dS )a¼  Sets the tooltip for a specified toolkit control.

        This uses the tooltip_text method to get the text to use.

        Parameters
        ----------
        control : optional toolkit control
            The toolkit control that is having the tooltip set.  If None
            then the editor's control is used.

        Returns
        -------
        tooltip_set : bool
            Whether or not a tooltip value could be set.
        NFT)Útooltip_textr5   r7   r4   r    r    r&   Úset_tooltip«  s    zEditor.set_tooltipc                 C   sF   | j r| j S | j | j¡}|j}|dur,|S |j}|durBd| S dS )a‡  Get the text for a tooltip, checking various sources.

        This checks for text from, in order:

        - the editor's description trait
        - the base trait's 'tooltip' metadata
        - the base trait's 'desc' metadata

        Returns
        -------
        text : str or None
            The text for the tooltip, or None if no suitable text can
            be found.
        Nz
Specifies )r/   r   Ú
base_traitrE   ZtooltipÚdesc)r$   rs   r6   r    r    r&   rq   Æ  s    zEditor.tooltip_textc                 C   s   | j S )a  Get the concrete widget for the control.

        The default implementation returns the control, however some editors
        in some backends may store a layout or sizer instead of a proper widget
        or control, which may not be suitable for certain usages.
        )r5   r(   r    r    r&   r.   å  s    zEditor.get_control_widgetc              	   c   sJ   || j v rdV  dS | j  |¡ zdV  W | j  |¡ n| j  |¡ 0 dS )z9Context manager that blocks updates from the named trait.N)Ú_no_trait_updaterP   rH   )r$   rE   r    r    r&   Úno_trait_updateð  s    
zEditor.no_trait_updatec                 c   s4   z
dV  W n$ t y.   ddlm} |ƒ  Y n0 dS )z=Context manager that uses raise to debug to raise exceptions.Nr   )rc   )Ú	ExceptionZtraitsui.apirc   )r$   rc   r    r    r&   rc   ý  s
    
zEditor.raise_to_debugc                 c   s4   | j rdV  dS d| _ zdV  W d| _ nd| _ 0 dS )z)Context manager to handle updating value.NTF)Úupdatingr(   r    r    r&   Úupdating_value  s    zEditor.updating_valuec                    s|   t ƒ jf i |¤Ž zt| j| jƒ| _W n> tyd   | j | j¡}|jdksV| jdkr^t	| _n‚ Y n0 |  
| jjdd¡ dS )zInitializes the editor object.ÚeventZspringÚinvalidr\   N)ÚsuperÚ__init__Úgetattrr   rE   rT   ÚAttributeErrorrs   Útyper   rl   r8   r{   )r$   r%   ÚtraitsZctrait©Ú	__class__r    r&   r}     s    zEditor.__init__c                 C   sœ   | j du rdS || jur(| j  | j¡| _| jdu rL| jj| j| jdd� dS | j	j
dkrŠ| |¡jdkrŠd| j _| jrŠ|  | j||||¡ | js˜|  ¡  dS )zrPerforms updates when the object trait changes.

        This is designed to be used as a trait listener.
        NTrG   Úreadonlyrz   )r>   r   Zget_extended_valueÚobject_namer5   rA   rB   rC   r@   rR   Ústylers   r€   Úmodifiedrx   rS   rW   r)   rV   r    r    r&   rC   ,  s(    




ÿ
ÿþÿzEditor._update_editorc              	   C   sÜ   | j }|jtd� ¡ D ]À\}}t||ƒ}|  |¡}|jr@|j}n|j}t|tƒrr|  |j	||t
|jƒ|jdk¡ q|jdurºt||jdƒdkrºt||jƒ}|  |||t
|jƒ|jdk¡ q|dkr|turt| ||ƒ qdS )aâ  Initialize and synchronize editor and factory traits

        Initializes and synchronizes (as needed) editor traits with the
        value of corresponding factory traits.  The name of the factory
        trait and the editor trait must match and the factory trait needs
        to have ``sync_value`` metadata set.  The strategy followed is:

        - for each factory trait with ``sync_value`` metadata:

          1.  if the value is a :class:`ContextValue` instance then
              call :meth:`sync_value` with the ``name`` from the
              context value.
          2.  if the trait has ``sync_name`` metadata, look at the
              referenced trait value and if it is a non-empty string
              then use this value as the name of the value in the
              context.
          3.  otherwise initialize the current value of the factory
              trait to the corresponding value of the editor.

        - synchronization mode in cases 1 and 2 is taken from the
          ``sync_value`` metadata of the editor trait first and then
          the ``sync_value`` metadata of the factory trait if that is
          empty.

        - if the value is a container type, then the `is_list` metadata
          is set to
        )rl   rz   NrY   r]   )r8   r�   r   Úitemsr~   Útraitrl   Ú
isinstancer   rE   Úboolrg   r€   Ú	sync_namer   rK   )r$   r8   rE   r‰   r:   Z
self_traitrf   rŒ   r    r    r&   rD   [  s:    


ûÿþûzEditor._sync_valuesc           	         sl   ‡ ‡‡fdd„}|  ||¡ ˆj |||f¡ |rh‡ ‡‡fdd„}|d }|  ||¡ ˆj |||f¡ dS )áœ  Bind trait change handlers from a user object to the editor.

        Parameters
        ----------
        key : str
            The key to use to guard against recursive updates.
        user_object : object
            The object in the TraitsUI context that is being bound.
        xuser_name: : str
            The extended name of the trait to be used on the user object.
        editor_name : str
            The name of the relevant editor trait.
        is_list : bool, optional
            If true, synchronization for item events will be set up in
            addition to the synchronization for the object itself.
            The default is False.
        c              	      sl   ˆˆj vrhˆ ˆ¡�D ˆ ¡ � tˆˆ | ƒ W d   ƒ n1 s@0    Y  W d   ƒ n1 s^0    Y  d S ©N©ru   rv   rc   r   ©Únew©re   rh   r$   r    r&   Úuser_trait_modified«  s    
z.Editor._bind_from.<locals>.user_trait_modifiedc              	      sŽ   t | tƒrŠˆˆjvrŠˆ ˆ¡�\ ˆ ¡ �4 | j}| jtˆˆ ƒ||t| j	ƒ …< W d   ƒ n1 sb0    Y  W d   ƒ n1 s€0    Y  d S rŽ   )
rŠ   r   ru   rv   rc   ÚindexÚaddedr~   r_   Úremoved)rz   Únr’   r    r&   Úuser_list_modifiedµ  s    ÿþþÿz-Editor._bind_from.<locals>.user_list_modifiedÚ_itemsN)rB   rJ   Úappend)	r$   rh   rj   rk   re   rg   r“   r˜   rˆ   r    r’   r&   rb   ˜  s    zEditor._bind_fromc                    sl   ‡ ‡‡‡fdd„}ˆ  ||¡ ˆj ||f¡ |rh‡ ‡‡‡fdd„}ˆ  ||d ¡ ˆj |d |f¡ dS )r�   c              	      sl   ˆ ˆj vrhˆ ˆ ¡�D ˆ ¡ � tˆˆ| ƒ W d   ƒ n1 s@0    Y  W d   ƒ n1 s^0    Y  d S rŽ   r�   r�   ©rh   r$   rj   rk   r    r&   Úeditor_trait_modified×  s    
z.Editor._bind_to.<locals>.editor_trait_modifiedc              	      sˆ   ˆ ˆj vr„ˆ ˆ ¡�` ˆ ¡ �8 | j}tˆˆƒ}| j|||t| jƒ …< W d   ƒ n1 s\0    Y  W d   ƒ n1 sz0    Y  d S rŽ   )ru   rv   rc   r”   r   r•   r_   r–   )rz   r—   r:   r›   r    r&   Úeditor_list_modifiedâ  s
    

z-Editor._bind_to.<locals>.editor_list_modifiedr™   N)rB   rI   rš   )r$   rh   rj   rk   re   rg   rœ   r�   r    r›   r&   rd   Ä  s    
ÿzEditor._bind_toc                 C   s¸   |   ¡ �œ zZ| jj}| j}| j}t|d||f dƒpLt|d| dƒpLt|dƒ}|| jj| j||ƒ W n0 ty” } z|  	|¡ ‚ W Y d}~n
d}~0 0 W d  ƒ n1 sª0    Y  dS )z¢Set the value of the trait the editor is editing.

        This calls the appropriate setattr method on the handler to perform
        the actual change.
        z%s_%s_setattrNz
%s_setattrrK   )
ry   r>   rL   r…   rE   r~   Úinfor   r   r2   )r$   r:   rL   Zobj_namerE   Úmethodr1   r    r    r&   Z__set_valueî  s    
ÿý
zEditor.__set_valuec                 C   s<   | j }| dd¡d }|dkr6|| jjv r6| jj| S | jS )zÇReturns the context object the editor is using

        In some cases a proxy object is edited rather than an object directly
        in the context, in which case we return ``self.object``.
        rZ   r   r   rY   )r…   r^   r>   r`   r   )r$   r…   Zcontext_keyr    r    r&   Ú_get_context_object  s
    zEditor._get_context_objectc                 C   s   d| j | jf  dd¡d S )z-Returns the extended trait name being edited.z%s.%srZ   r   )r…   rE   r^   r(   r    r    r&   Ú_get_extended_name  s    zEditor._get_extended_namec                 C   s   | j  | j¡S )zBReturns the trait the editor is editing (Property implementation).)r   r‰   rE   r(   r    r    r&   Ú_get_value_trait  s    zEditor._get_value_traitc                 C   s   t | j| jtƒS )z5Returns the value of the trait the editor is editing.)r~   r   rE   r   r(   r    r    r&   Ú
_get_value  s    zEditor._get_valuec                 C   s$   | j r | jdkr | j  | j|¡ dS )z£Set the value of the trait the editor is editing.

        Dispatches via the TraitsUI Undo/Redo mechanisms to make change
        reversible, if desired.
        r=   N)r>   rE   Zdo_undoableÚ_Editor__set_value)r$   r:   r    r    r&   Ú
_set_value"  s    zEditor._set_valuec                 C   s   |   t| j| jtƒ¡S )z4Returns the text representation of the object trait.)r9   r~   r   rE   r   r(   r    r    r&   Ú_get_str_value+  s    zEditor._get_str_value)N)rX   FF)N)KÚ__name__Ú
__module__Ú__qualname__Ú__doc__r	   r>   r   r…   r   r   r   rE   r   rA   r@   r   rT   r/   r   rR   r5   Zlabel_controlr   ZenabledZvisibleZ
scrollabler   r8   rx   r:   Z	str_valueZvalue_traitr{   r   ru   r
   r   r   rJ   rI   r'   r)   r2   r3   r7   r9   r;   r<   rF   rM   rS   rW   rl   rp   rr   rq   r.   r   rv   rc   ry   r}   rC   rD   rb   rd   r¤   r   r    r¡   r¢   r£   r¥   r¦   Ú__classcell__r    r    r‚   r&   r   2   s€   



   ú
F


	
/=,*

	r   N)$rª   Ú
contextlibr   Ú	functoolsr   Z
traits.apir   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   Ztraits.trait_baser   r   r   Zeditor_factoryr   Zcontext_valuer   Zundor   rR   r   Zfactory_traitr   r    r    r    r&   Ú<module>   s   H