
    lh.                        d Z ddlZddlZddlZddlZddlmZ ddlmZm	Z	 ddl
mZmZ ddlmZ dZd	 Zd
 Zi ad Zd Zej        d             Z G d de          Z G d deee          Z G d dej                  Z e            ZdS )z:mod:`wand.resource` --- Global resource management
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

There is the global resource to manage in MagickWand API. This module
implements automatic global resource management through reference counting.

    N   )library)abcstring_type)TYPE_MAPWandException)MAGICK_VERSION_NUMBER)genesislimitsshutdownterminusDestroyedResourceErrorResourceResourceLimitsc                  ,    t          j                     dS )zInstantiates the MagickWand API.

    .. warning::

       Don't call this function directly. Use :func:`increment_refcount()` and
       :func:`decrement_refcount()` functions instead.

    N)r   MagickWandGenesis     P/var/www/html/research.buxo.ca/env/lib/python3.11/site-packages/wand/resource.pyr
   r
      s     r   c                      t           j        t          j                     dS t          j                    rt          j                     dS dS )zCleans up the MagickWand API.

    .. warning::

       Don't call this function directly. Use :func:`increment_refcount()` and
       :func:`decrement_refcount()` functions instead.

    N)r   IsMagickWandInstantiatedMagickWandTerminusr   r   r   r   r   "   sR     '/"$$$$$		)	+	+ %"$$$$$% %r   c                 n    t          t                    dk    rt                       | r|t          | <   d S d S Nr   )lenallocation_mapr
   addrdeallocators     r   allocate_refr    4   s@    
>a			 +*t+ +r   c                     | t          t                    v r6t                              |           }t          |          r ||            d S d S d S N)listr   popcallabler   s     r   deallocate_refr&   <   s`    tN####$((..K   	K $#	 	r   c                      t          t                    D ]G} 	 t                              |           }t          |          r ||            8# t          $ r Y Dw xY wt                       d S r"   )r#   r   r$   r%   KeyErrorr   r   s     r   r   r   D   s     ^$$  	(,,T22K$$ "D!!! 	 	 	D	JJJJJs   4A
AAc                       e Zd ZdZeZeZeZeZe	d             Z
e
j        d             Z
e
j        d             Z
ej        d             Zd Zd Zdd	ZddZd Zd Zd Zd
S )r   a  Abstract base class for MagickWand object that requires resource
    management. Its all subclasses manage the resource semiautomatically
    and support :keyword:`with` statement as well::

        with Resource() as resource:
            # use the resource...
            pass

    It doesn't implement constructor by itself, so subclasses should
    implement it. Every constructor should assign the pointer of its
    resource data into :attr:`resource` attribute inside of :keyword:`with`
    :meth:`allocate()` context.  For example::

        class Pizza(Resource):
            '''My pizza yummy.'''

            def __init__(self):
                with self.allocate():
                    self.resource = library.NewPizza()

    .. versionadded:: 0.1.2

    c                 p    t          | dd          t          t          |           dz             | j        S )zInternal pointer to the resource instance. It may raise
        :exc:`DestroyedResourceError` when the resource has destroyed already.

        
c_resourceNz is destroyed already)getattrr   reprr+   selfs    r   resourcezResource.resource   s8     4t,,4(d6M)MNNNr   c                     t          | dd           r|                                  |                     |          r#|| _        t	          | j        | j                   d S t          t          |          dz             )Nr+   z is an invalid resource)r,   destroyc_is_resourcer+   r    c_destroy_resource	TypeErrorr-   r/   r0   s     r   r0   zResource.resource   sx     4t,, 	LLNNNh'' 	H&DO$*ABBBBBDNN-FFGGGr   c                 ^    t          | dd           rt          | j                   d | _        d S )Nr+   )r,   r&   r+   r.   s    r   r0   zResource.resource   s1    4t,, 	,4?+++r   c              #   .   K   t                       | V  dS )a$  Allocates the memory for the resource explicitly. Its subclasses
        should assign the created resource into :attr:`resource` attribute
        inside of this context. For example::

            with resource.allocate():
                resource.resource = library.NewResource()

        N)r
   r.   s    r   allocatezResource.allocate   s       				




r   c                 
    | ` dS )zCleans up the resource explicitly. If you use the resource in
        :keyword:`with` statement, it was called implicitly so have not to
        call it.

        N)r0   r.   s    r   r2   zResource.destroy   s     MMMr   c                    t          j                    }|                     | j        t          j        |                    }|j        dk    r|rt          j        |          }dS |                     | j                   t          |j                 }|r)t          j
        |          }t          j        |          }nd}t          |t                    s|                    d          } ||          S )zGets a current exception instance.

        :returns: a current exception. it can be ``None`` as well if any
                  errors aren't occurred
        :rtype: :class:`wand.exceptions.WandException`

        r   Nr   replace)errors)ctypesc_intc_get_exceptionr0   byrefvaluer   MagickRelinquishMemoryc_clear_exceptionr   	string_at
isinstancer   decode)r/   severitydescexc_clsmessages        r   get_exceptionzResource.get_exception   s     <>>##DM6<3I3IJJ>Q <5d;;Ft}---8>* 	&t,,G1$77DDG';// 	7nnIn66Gwwr   r   c                     |                                  }t          |t                    rt          j        ||dz              dS t          |t
                    r|dS )z2Raises an exception or warning if it has occurred.r   )
stacklevelN)rL   rF   Warningwarningswarn	Exception)r/   rN   es      r   raise_exceptionzResource.raise_exception   se      a!! 	M!
Q7777779%% 	G	 	r   Nc                     t           r"   )NotImplementedError)r/   formats     r   	make_blobzResource.make_blob   s    !!r   c                     | S r"   r   r.   s    r   	__enter__zResource.__enter__   s    r   c                 .    |                                   d S r"   )r2   )r/   typerB   	tracebacks       r   __exit__zResource.__exit__   s    r   c                 R    	 |                                   d S # t          $ r Y d S w xY wr"   )r2   r   r.   s    r   __del__zResource.__del__   s:    	LLNNNNN% 	 	 	DD	s    
&&)r   r"   )__name__
__module____qualname____doc__NotImplementedr3   r4   r@   rD   propertyr0   setterdeleter
contextlibcontextmanagerr9   r2   rL   rT   rX   rZ   r^   r`   r   r   r   r   r   Q   s'        @ #M ( %O '  X _	H 	H _	H   
          2   " " " "        r   r   c                       e Zd ZdZdS )r   zAn error that rises when some code tries access to an already
    destroyed resource.

    .. versionchanged:: 0.3.0
       It becomes a subtype of :exc:`wand.exceptions.WandException`.

    N)ra   rb   rc   rd   r   r   r   r   r      s           r   r   c                   V    e Zd ZdZdZdZd Zd Zd Zd Z	d Z
d	 Zd
 Zd Zd Zd ZdS )r   a  Wrapper for MagickCore resource limits.
    Useful for dynamically reducing system resources before attempting risky,
    or slow running, :class:`~wand.image.Image` operations.

    For example::

       from wand.image import Image
       from wand.resource import limits

       # Use 100MB of ram before writing temp data to disk.
       limits['memory'] = 1024 * 1024 * 100
       # Reject images larger than 1000x1000.
       limits['width'] = 1000
       limits['height'] = 1000

       # Debug resources used.
       with Image(filename='user.jpg') as img:
           print('Using {0} of {1} memory'.format(limits.resource('memory'),
                                                  limits['memory']))

       # Dump list of all limits.
       for label in limits:
           print('{0} => {1}'.format(label, limits[label]))

    Available resource keys:

    - ``'area'`` - Maximum `width * height` of a pixel cache before writing to
      disk.
    - ``'disk'`` - Maximum bytes used by pixel cache on disk before exception
      is thrown.
    - ``'file'`` - Maximum cache files opened at any given time.
    - ``'height'`` - Maximum height of image before exception is thrown.
    - ``'list_length'`` - Maximum images in sequence. Only available with
      recent version of ImageMagick.
    - ``'map'`` - Maximum memory map in bytes to allocated for pixel cache
      before using disk.
    - ``'memory'`` - Maximum bytes to allocated for pixel cache before using
      disk.
    - ``'thread'`` - Maximum parallel task sub-routines can spawn - if using
      OpenMP.
    - ``'throttle'`` - Total milliseconds to yield to CPU - if possible.
    - ``'time'`` - Maximum seconds before exception is thrown.
    - ``'width'`` - Maximum width of image before exception is thrown.

    .. versionadded:: 0.5.1
    )	undefinedareadiskfilemapmemorythreadtimethrottlewidthheight)rm   rn   ro   rp   rw   rq   rr   rs   ru   rt   rv   list_lengthc                 P    t           dk     r| j        | _        d S | j        | _        d S )Ni   )r	   _limits6r   _limits7r.   s    r   __init__zResourceLimits.__init__5  s'     5((-DKKK-DKKKr   c                 ,    |                      |          S r"   )get_resource_limitr/   rs     r   __getitem__zResourceLimits.__getitem__;  s    &&q)))r   c                 2    |                      ||           d S r"   )set_resource_limit)r/   r   vs      r   __setitem__zResourceLimits.__setitem__>  s    1%%%%%r   c                     d| |<   d S r   r   r   s     r   __delitem__zResourceLimits.__delitem__A  s    Qr   c                 *    t          | j                  S r"   )iterr   r.   s    r   __iter__zResourceLimits.__iter__D  s    DK   r   c                 *    t          | j                  S r"   )r   r   r.   s    r   __len__zResourceLimits.__len__G  s    4;r   c                 6    | j                             |          S )z3Helper method to map resource string to enum value.)r   indexr6   s     r   _to_idxzResourceLimits._to_idxJ  s    {  ***r   c                 P    t          j        |                     |                    S )zGet the current value for the resource type.

        :param resource: Resource type.
        :type resource: :class:`basestring`
        :rtype: :class:`numeric.Integral`

        .. versionadded:: 0.5.1
        )r   MagickGetResourcer   r6   s     r   r0   zResourceLimits.resourceN  s!     (h)?)?@@@r   c                 l    t                       t          j        |                     |                    S )zGet the current limit for the resource type.

        :param resource: Resource type.
        :type resource: :class:`basestring`
        :rtype: :class:`numeric.Integral`

        .. versionadded:: 0.5.1
        )r
   r   MagickGetResourceLimitr   r6   s     r   r~   z!ResourceLimits.get_resource_limitY  s*     				-dll8.D.DEEEr   c                     t                       t          j        |          }t          j        |                     |          |           dS )a  Sets a new limit for resource type.

        .. note::

            The new limit value must be equal to or less than the maximum
            limit defined by the :file:`policy.xml`. Any values set outside
            normal bounds will be ignored silently.

        :param resource: Resource type.
        :type resource: :class:`basestring`
        :param limit: New limit value.
        :type limit: :class:`numeric.Integral`

        .. versionadded:: 0.5.1
        N)r
   r>   c_ulonglongr   MagickSetResourceLimitr   )r/   r0   limitulls       r   r   z!ResourceLimits.set_resource_limite  sB      				 ''&t||H'='=sCCCCCr   N)ra   rb   rc   rd   rz   r{   r|   r   r   r   r   r   r   r0   r~   r   r   r   r   r   r      s        - -`7HFH( ( (* * *& & &  ! ! !     + + +	A 	A 	A
F 
F 
FD D D D Dr   r   )rd   atexitri   r>   rP   apir   compatr   r   
exceptionsr   r   versionr	   __all__r
   r   r   r    r&   registerr   objectr   ReferenceErrorAttributeErrorr   MutableMappingr   r   r   r   r   <module>r      s                 $ $ $ $ $ $ $ $ / / / / / / / / * * * * * *C	  	  	 % % % + + +   	 	 	_ _ _ _ _v _ _ _D    ]NN   zD zD zD zD zDS' zD zD zD@ 
		r   