o
    Uh$                     @   s:  d Z ddlmZ ddlmZ ddlZddlZddlmZ ddl	Z	ddl
mZmZ ddlmZmZ ddlmZ dd	lmZmZ dd
lmZ ddlmZ ddlmZmZ ddlmZmZm Z m!Z! ddl"m#Z#m$Z$m%Z%m&Z&m'Z' g dZ(G dd de)Z*G dd de Z+d ddZ,G dd dZ-G dd deZ.ed!ddZ/dS )"z+Synchronous IO wrappers with thread safety
    )Future)contextmanagerN)
EVENT_READ)QueueFull)LockThread)Optional)MessageMessageType)get_bus)message_bus)	ProxyBase
unwrap_msg   )unwrap_readprep_socketDBusConnectionBasetimeout_to_deadline)MessageFiltersFilterHandleReplyMatcherRouterClosedcheck_replyable)open_dbus_connectionopen_dbus_routerDBusConnection
DBusRouterProxyReceiveStoppedc                   @   s   e Zd ZdS )r   N)__name__
__module____qualname__ r#   r#   h/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/jeepney/io/threading.pyr   "   s    r   c                       sp   e Zd Zddejf fddZddefddZdd	d
efddZdddZdd Z	dd Z
 fddZ  ZS )r   Fsockc                    sF   t  j||d t \| _| _| j| jt| _	t
 | _t
 | _d S )N)
enable_fds)super__init__ospipe_stop_r_stop_wselectorregisterr   stop_keyr   	send_lockrcv_lock)selfr%   r&   	__class__r#   r$   r(   '   s
   zDBusConnection.__init__Nmessagec                 C   sj   |  ||\}}| j  |r| || n| j| W d   dS W d   dS 1 s.w   Y  dS ).Serialise and send a :class:`~.Message` objectN)
_serialiser0   _send_with_fdsr%   sendall)r2   r5   serialdatafdsr#   r#   r$   send.   s   "zDBusConnection.sendtimeoutreturnc                C   sN   t |}| jj|p
ddstd| dz| |W | j  S | j  w )a  Return the next available message from the connection

        If the data is ready, this will return immediately, even if timeout<=0.
        Otherwise, it will wait for up to timeout seconds, or indefinitely if
        timeout is None. If no message comes in time, it raises TimeoutError.

        If the connection is closed from another thread, this will raise
        ReceiveStopped.
        r>   zDid not get receive lock in z seconds)r   r1   acquireTimeoutError_receiverelease)r2   r?   deadliner#   r#   r$   receive7   s   

zDBusConnection.receivec                 C   s`   | j |D ]'\}}|| jkr$| jr|    S t| jdg f  S || jkr-t	dqt
)Ni   z(DBus receive stopped from another thread)r-   select
select_keyr&   _read_with_fdsr   r%   recvr/   r   rC   )r2   r?   keyevr#   r#   r$   _read_some_dataJ   s   

zDBusConnection._read_some_datac                 C   s   t | jd dS )z;Make any threads waiting for a message raise ReceiveStopped   aN)r)   writer,   r2   r#   r#   r$   	interruptW   s   zDBusConnection.interruptc                 C   sF   | j tf| jjddv r!t| jd | j tf| jjddv sdS dS )zAllow calls to .receive() again after .interrupt()

        To avoid race conditions, you should typically wait for threads to
        respond (e.g. by joining them) between interrupting and resetting.
        r   r>   i   N)r/   r   r-   rH   r)   readr+   rQ   r#   r#   r$   reset_interrupt[   s    zDBusConnection.reset_interruptc                    s   |    t   dS )zClose the connectionN)rR   r'   closerQ   r3   r#   r$   rU   e   s   zDBusConnection.close)FN)r    r!   r"   socketr(   r
   r=   rG   rN   rR   rT   rU   __classcell__r#   r#   r3   r$   r   &   s    	

r   SESSIONF      ?c                 C   sj   t | }t|||d}t||}t|}tt|dd }|d |_W d   |S 1 s.w   Y  |S )aR  Open a plain D-Bus connection

    D-Bus has an authentication step before sending or receiving messages.
    This takes < 1 ms in normal operation, but there is a timeout so that client
    code won't get stuck if the server doesn't reply. *auth_timeout* configures
    this timeout in seconds.

    :return: :class:`DBusConnection`
    r>   
   r   N)r   r   r   r   r   r   Hellounique_name)busr&   auth_timeoutbus_addrr%   connrouter
reply_bodyr#   r#   r$   r   k   s   



r   c                   @   s   e Zd ZdZdefddZedd Zddd	d
Zddde	de	fddZ
dd Zdd Zdd Zddddee fddZde	fddZdd ZdS )r   aU  A client D-Bus connection which can wait for replies.

    This runs a separate receiver thread and dispatches received messages.

    It's possible to wrap a :class:`DBusConnection` in a router temporarily.
    Using the connection directly while it is wrapped is not supported,
    but you can use it again after the router is closed.
    ra   c                 C   s4   || _ t | _t | _t| jdd| _| j  d S )NT)targetdaemon)	ra   r   _repliesr   _filtersr   	_receiver_rcv_threadstart)r2   ra   r#   r#   r$   r(      s
   zDBusRouter.__init__c                 C   s   | j jS rV   )ra   r]   rQ   r#   r#   r$   r]      s   zDBusRouter.unique_nameNr:   c                C   s   | j j||d dS )r6   rk   N)ra   r=   )r2   r5   r:   r#   r#   r$   r=      s   zDBusRouter.sendr>   msgr@   c                C   sv   t | | j stdt| jj}| j|t	 }| jj
||d |j|dW  d   S 1 s4w   Y  dS )z7Send a method call message, wait for and return a replyzThis D-Bus router has stoppedrk   r>   N)r   ri   is_aliver   nextra   outgoing_serialrf   catchr   r=   result)r2   rl   r?   r:   	reply_futr#   r#   r$   send_and_get_reply   s   

$zDBusRouter.send_and_get_replyc                 C   s&   | j   | jjdd | j   dS )zRClose this router

        This does not close the underlying connection.
        r[   r>   N)ra   rR   ri   joinrT   rQ   r#   r#   r$   rU      s   
zDBusRouter.closec                 C   s   | S rV   r#   rQ   r#   r#   r$   	__enter__   s   zDBusRouter.__enter__c                 C   s   |    dS )NF)rU   )r2   exc_typeexc_valexc_tbr#   r#   r$   __exit__   s   zDBusRouter.__exit__r   )queuebufsizerz   c                C   s   t | j||p
t|dS )a}  Create a filter for incoming messages

        Usage::

            with router.filter(rule) as queue:
                matching_msg = queue.get()

        :param jeepney.MatchRule rule: Catch messages matching this rule
        :param queue.Queue queue: Matched messages will be added to this
        :param int bufsize: If no queue is passed in, create one with this size
        )maxsize)r   rg   r   )r2   rulerz   r{   r#   r#   r$   filter   s   zDBusRouter.filterc              	   C   sH   | j |rd S | j|D ]}z|j| W q ty!   Y qw d S rV   )rf   dispatchrg   matchesrz   
put_nowait	QueueFull)r2   rl   r~   r#   r#   r$   	_dispatch   s   zDBusRouter._dispatchc                 C   sJ   zz	 | j  }| | q ty   Y nw W | j  d S | j  w rV   )ra   rG   r   r   rf   drop_all)r2   rl   r#   r#   r$   rh      s   

zDBusRouter._receiver)r    r!   r"   __doc__r   r(   propertyr]   r=   r
   rs   rU   ru   ry   r	   r   r~   r   rh   r#   r#   r#   r$   r      s    
	
r   c                       s6   e Zd ZdZdd fdd
Zdd Zdd	 Z  ZS )
r   az  A blocking proxy for calling D-Bus methods via a :class:`DBusRouter`.

    You can call methods on the proxy object, such as ``bus_proxy.Hello()``
    to make a method call over D-Bus and wait for a reply. It will either
    return a tuple of returned data, or raise :exc:`.DBusErrorResponse`.
    The methods available are defined by the message generator you wrap.

    You can set a time limit on a call by passing ``_timeout=`` in the method
    call, or set a default when creating the proxy. The ``_timeout`` argument
    is not passed to the message generator.
    All timeouts are in seconds, and :exc:`TimeoutErrror` is raised if it
    expires before a reply arrives.

    :param msggen: A message generator object
    :param ~threading.DBusRouter router: Router to send and receive messages
    :param float timeout: Default seconds to wait for a reply, or None for no limit
    Nr>   c                   s   t  | || _|| _d S rV   )r'   r(   _router_timeout)r2   msggenrb   r?   r3   r#   r$   r(      s   
zProxy.__init__c                 C   s4   | j d u rdnd| j  }d| j d| j | dS )N z
, timeout=zProxy(z, ))r   _msggenr   )r2   extrar#   r#   r$   __repr__   s   zProxy.__repr__c                    s   t   fdd}|S )Nc                     sF   | dj} | i |}|jjtju sJ jj||d}t|S )Nr   r>   )	popr   headermessage_typer   method_callr   rs   r   )argskwargsr?   rl   replymake_msgr2   r#   r$   inner   s
   z!Proxy._method_call.<locals>.inner)	functoolswraps)r2   r   r   r#   r   r$   _method_call   s   zProxy._method_call)r    r!   r"   r   r(   r   r   rX   r#   r#   r3   r$   r      s
    r   c              	   c   sr    t | |d(}t|}|V  W d   n1 sw   Y  W d   dS W d   dS 1 s2w   Y  dS )a  Open a D-Bus 'router' to send and receive messages.

    Use as a context manager::

        with open_dbus_router() as router:
            ...

    On leaving the ``with`` block, the connection will be closed.

    :param str bus: 'SESSION' or 'SYSTEM' or a supported address.
    :param bool enable_fds: Whether to enable passing file descriptors.
    :return: :class:`DBusRouter`
    )r^   r&   N)r   r   )r^   r&   ra   rb   r#   r#   r$   r      s   
"r   )rY   FrZ   )rY   F)0r   concurrent.futuresr   
contextlibr   r   r)   	selectorsr   rW   rz   r   r   r   	threadingr   r   typingr	   jeepneyr
   r   jeepney.busr   jeepney.bus_messagesr   jeepney.wrappersr   r   blockingr   r   r   r   commonr   r   r   r   r   __all__	Exceptionr   r   r   r   r   r   r#   r#   r#   r$   <module>   s0    

EY&