
    ^j                   l   d dl m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T d dlm	Z	 d dl
mZmZmZmZ ddlT d ej        d	          z  d
k    Z ej                    dk    Z ej                    dk    Z ee          dk    reZn ee          dk    reZ e	j        d          ZedZe                    e          Ze                     e	j        d                    Zdej         _!        egej         _"        e#e e$e%          ee%gej&        _"        e'ej&        _!        dWdZ(dXdZ)e*ej+        _!        ee#e%e,e#gej+        _"        e*ej-        _!        e*ej.        _!        eegej.        _"        e*ej/        _!        eegej/        _"         e$e          ej0        _!        e e$e1          gej0        _"         e$e          ej2        _!        e e$e1          gej2        _"         e$e          ej3        _!        e e$e1          gej3        _"         e$e          ej4        _!        e e$e1          gej4        _"        eej5        _!        ee%gej5        _"        eej6        _!        eegej6        _"        eej7        _!        ee#gej7        _"        eej8        _!        eegej8        _"        e%ej9        _!        egej9        _"        eej:        _!        ee#gej:        _"        e#ej;        _!        egej;        _"        eej<        _!        eegej<        _"        eseej=        _!        eegej=        _"        e#ej>        _!        egej>        _"        eej?        _!        ee#gej?        _"        eej@        _!        egej@        _"        e'ejA        _!        egejA        _"        e#ejB        _!        egejB        _"        e*ejC        _!        egejC        _"        eejD        _!        eeee#gejD        _"        e*ejE        _!        eegejE        _"        dejF        _!        ee#gejF        _"        eejG        _!        eegejG        _"        dejH        _!        ee'gejH        _"        dejI        _!        ee#gejI        _"        e#ejJ        _!        egejJ        _"        eejK        _!        egejK        _"        e#ejL        _!        egejL        _"        e#ejM        _!        ee1gejM        _"         e$eN          ejO        _!        egejO        _"        dejP        _!        eegejP        _"        dejQ        _!        ee1e#e%gejQ        _"        eejR        _!        egejR        _"        eejS        _!        egejS        _"        e1ejT        _!        egejT        _"        dejU        _!        ee#e%gejU        _"        e#ejV        _!        egejV        _"        eejW        _!        eegejW        _"        eejX        _!        ee#e%gejX        _"         e$e          ejY        _!         e$e'          gejY        _"        eejZ        _!        eegejZ        _"        eej[        _!        e#gej[        _"        e'ej\        _!        ee'gej\        _"        eej]        _!        e#gej]        _"        eej^        _!        e#gej^        _"        esdej_        _!        esdej`        _!        deja        _!        egeja        _"        dejb        _!        egejb        _"        dejc        _!        eeee'gejc        _"        eejd        _!        ee%gejd        _"        eeje        _!        egeje        _"        eejf        _!        egejf        _"        e#ejg        _!        egejg        _"        eejh        _!        ee#egejh        _"        eeji        _!        eegeji        _"        eejj        _!        eegejj        _"        eejk        _!        dejl        _!        eeegejl        _"        e#ejm        _!        egejm        _"        e#ejn        _!        egejn        _"        e*ejo        _!        eegejo        _"         G d dep          Zq e$eq          ejr        _!        ee*e* e$e1          gejr        _"        eejs        _!        e e$e1          gejs        _"         e$e          e_t        e e$e1          gejt        _"        eqeju        _!        eee*e*geju        _"        e#ejv        _!        egejv        _"        e#ejw        _!        egejw        _"        e*ejx        _!        eegejx        _"        eejy        _!        e#gejy        _"        eejz        _!        g ejz        _"        dej{        _!        egej{        _"        d Z|dZ}dZ~dYdZdZd Zd[d"Zd\d$Zd]d%Zd\d&Zd^d*Zd^d+Z ed,          Zedd-d_d5Z G d6 d7ep          Z e$e          Zdd8d9Zi Zd: Zd; Zd< Zd= Zd> Zd? Zd@ ZdA Z G dB dC          Z G dD dE          Z G dF dG          Z G dH dI          Z e            Z G dJ dK          ZdL ZdM Z G dN dO          ZegZi Z G dP dQ          ZdR Zd`dSZdT ZdU ZedV             ZdS )a    )annotationsN)contextmanager)*)util)TypeTypeVarSequenceAny      P@   i386arm64   objcz/usr/lib/libobjc.dylibcnamestrreturnc                P   |                      d          }t                      }t                              |d t	          |          d d           t          |j                  }t                              ||t	          |          d d           |j                            d          S )Nzutf-8r   )encodec_size_tlibcsysctlbynamebyrefcreate_string_buffervaluedecode)r   
name_bytessizebufs       ]/home/agentuser/manim-venv/lib/python3.11/site-packages/pyglet/libs/darwin/cocoapy/runtime.py_sysctl_getr$   H   s    W%%J::Dj$dT1===
tz
*
*Cj#uT{{D!<<<9G$$$    c                     	 t          d          S # t          $ r% 	 t          d          cY S # t          $ r Y Y dS w xY ww xY w)z?Return Apple chip model name.

    For example: "Apple M2"
    zmachdep.cpu.brand_stringzhw.modelUnknown)r$   	Exception r%   r#   get_chip_modelr*   S   sn    
5666   	z***** 	 	 	999	s$    
A -A 
<A <A c                      e Zd ZdefdefgZdS )OBJC_METHOD_DESCRIPTIONr   typesN)__name__
__module____qualname__c_void_pc_char_p_fields_r)   r%   r#   r,   r,     s"        "Wh$78HHHr%   r,   i  i  xbytes | strbytesc                Z    t          | t                    r| S |                     d          S )a  Attempt to encode an object as :py:class:`bytes`.

    If it is already :py:class:`bytes`, it will be returned as-is.
    Otherwise, this function attempt to convert ``x`` by assuming it
    has a string-like :py:meth:`~str.encode` method supporting
    ``'ascii'`` as an argument.

    Args:
        x: A :py:class:`bytes` or object with a string-like
         :py:meth:`~str.encode` method.

    Returns:
        :py:class:`bytes`
    ascii)
isinstancer6   r   )r4   s    r#   ensure_bytesr:     s-     !U 88Gr%   str | bytesr1   c                j    t          t                              t          |                               S )ad  Return a void pointer for a named ObjectiveC selector.

    See Apple's developer documentation on ``sel_registerName``:
    https://developer.apple.com/documentation/objectivec/1418557-sel_registername

    Args:
        name:
            An ObjectiveC selector name as bytes or a str

    Returns:
        A void pointer for the ObjectiveC selector.
    )r1   r   sel_registerNamer:   r   s    r#   get_selectorr?     s(     D)),t*<*<==>>>r%   c_void_p | Nonec                j    t          t                              t          |                               S )a  Try to get a ctypes void pointer for the named ObjectiveC class.

    If no class with the name exists, this function returns None
    instead.

    See Apple's developer documentation for ``objc_getClass``:
    https://developer.apple.com/documentation/objectivec/1418952-objc_getclass

     Args:
        name:
            A name of an ObjectiveC class as a Python bytes or string
            object.

    Returns:
        A void pointer to the class or None if it wasn't found.
    )r1   r   objc_getClassr:   r>   s    r#   	get_classrC     s(    " D&&|D'9'9::;;;r%   objc                P    t          t                              |                     S )af  Get the ObjectiveC class for an object or None if it's nil.

    See Apple's developer documentation for ``object_GetClass``.
    https://developer.apple.com/documentation/objectivec/1418629-object_getclass/

    Args:
        obj:
            A void pointer to an ObjectiveC object.

    Returns:
         A void pointer to the ObjectiveC class object.
    )r1   r   object_getClass)rD   s    r#   get_object_classrG     s      D((--...r%   c                j    t          t                              t          |                               S )a  Try to get a pointer to the metaclass for an ObjectiveC class name.

    If the class isn't registered with the ObjectiveC runtime, returns
    None.

    See the following to learn more:

    * Sealie Software's explanation of ObjectiveC metaclasses:
      https://www.sealiesoftware.com/blog/archive/2009/04/14/objc_explain_Classes_and_metaclasses.html
    * Apple's developer documentation for ``objc_getMetaClass``:
      https://developer.apple.com/documentation/objectivec/1418721-objc_getmetaclass/

    Args:
        name:
            The name of an ObjectiveC class as a Python string or
            bytes object.
    Returns:
         A void pointer if an ObjectiveC metaclass was found for the
         class name, or None if it wasn't.
    )r1   r   objc_getMetaClassr:   r>   s    r#   get_metaclassrJ     s(    * D**<+=+=>>???r%   c                    t          t                              |                     }t          t                              |                    S )a  Try to get a pointer to the ObjectiveC superclass of an object.

    See the following to learn more:
    * https://developer.apple.com/documentation/objectivec/1418629-object_getclass/
    * https://developer.apple.com/documentation/objectivec/1418498-class_getsuperclass

    Args:
        obj:
            A pointer to an ObjectiveC object.

    Returns:
        * None if the object is Nil or an instance of a root class
        * Otherwise, a ctypes void pointer to ``obj``'s ObjectiveC superclass

    )r1   r   rF   class_getSuperclass)rD   clss     r#   get_superclass_of_objectrN   4  s;      4'',,
-
-CD,,S11222r%   restyper   boolc                    t          |           t          t                    k    rdS t          st          |           dk    rdS t          rt          |           dk    rdS dS )a  True when a message should be sent via struct-specific function.

    Usually, a message which returns a data structure should be sent via
    ``objc_msgSend_stret``. On some platforms, a data structure below a
    platform-specific size can instead be returned via the stack as a
    simple return value.

    This function returns ``True`` if the passed message result type
    seems big enough to use `obj_msgSend_stret` instead of other message
    sending functions.

    Note that this is a best guess based on available information. See
    the following to learn more:

    * Sealie Software's overview of objc_msgSend_stret
      http://www.sealiesoftware.com/blog/archive/2008/10/30/objc_explain_objc_msgSend_stret.html
    * Apple's developer documentation for objc_msgSend_stret
      http://www.sealiesoftware.com/blog/archive/2008/10/30/objc_explain_objc_msgSend_stret.html
    * Pages 20-27 of The System V ABI (The Stack Frame)
      https://cs61.seas.harvard.edu/site/pdf/x86-64-abi-20210928.pdf

    Args:
        restype:
            A :py:mod:`ctypes` representation of an ObjectiveC message
            result's type.
    Returns:
         ``True`` if it seems `objc_msgSend_stret` should be used;
         ``False`` if it shouldn't.
    Fr      T)type	Structure__LP64__sizeofrO   s    r#   x86_should_use_stretrX   I  s_    < G}}Y''u w1,,u F7OOr))u4r%   c                ~    t           sdS t          r| t          k    rdS t          s| t          t          t          fv rdS dS )a,  True if the result type is known to need a non-integer call

    On Macs running on x86 or amd64 processors, ObjectiveC messages
    returning non-integer data types may need to be sent using
    `objc_msgSend_fpret`_. This function returns ``True`` if the
    current processor and platform features indicate this is the case.

    To learn more, see:

    * Sealie Software'e overview of objc_msgSend_fpret:
      http://www.sealiesoftware.com/blog/archive/2008/11/16/objc_explain_objc_msgSend_fpret.html
    * Apple's developer documentation on objc_msgSend_fpret:
      https://developer.apple.com/documentation/objectivec/1456697-objc_msgsend_fpret

    Args:
        restype: A :py:mod:`ctypes` type.

    Returns:
        ``True`` if `objc_msgSend_fpret`_ should be used, ``False``
        otherwise.
    FT)__i386__rU   c_longdoublec_floatc_doublerW   s    r#   should_use_fpretr^   q  sK    ,  u G|++t GX|#DDDt5r%   _CTypesResType)rO   argtypesreceiverstr | c_void_p | ObjCInstanceselector_nameType[_CTypesResType]r`   Sequence[Type] | None_CTypesResType | Nonec               "   t          | t                    rt          |           } |sg }t          |          }t	          |          rY|t
          j        _        t          t          g}|	                    |           |t
          j        _
        t          j        | |g|R  }nt          |          rnt          |          t          t          g}|	                    |           |t
          j        _
         |            }t          j        t          |          | |g|R   nr|t
          j        _        t          t          g}|	                    |           |t
          j        _
        t          j        | |g|R  }|t          k    rt          |          }|S )a  Send an ObjectiveC message and return the result's value.

    **WARNING: On ARM64, ``argtypes`` is mandatory**!

    This function chooses the best known approach for sending the
    message based on:

    * Whether ``restype`` is a float or double type
    * ``sizeof(restype)``
    * Platform-specific stack behavior

    The ctypes objects passed to ``args`` must match the ctypes types in
    ``argytypes``. Unspecified ``argtypes`` are handled differently by
    different system architectures:

    * On ARM64, the function fails
    * On x86 / AMD64, all ``args`` assumed to be wrapped in c_void_p

    New code should specify the ``argtypes`` since all new Macs will be
    ARM64 for the foreseeable future.

    To learn more about ObjectiveC's message sending, see:

    * https://docs.python.org/3.8/library/ctypes.html#calling-variadic-functions
    * The x86_should_use_stret function in this file
    * The should_use_fpret function in this file
    * Apple's developer documentation on objc_msgSend:
      https://developer.apple.com/documentation/objectivec/1456712-objc_msgsend

    Args:
        receiver:
            A Python string for a class name or a c_void_p to an
            ObjectiveC class.
        selector_name:
            A selector name as Python string or bytes object
        *args:
            ctypes objects to send as the message arguments. These must
            match the types in ``argtypes`` if they're specified.
        restype:
            A ctypes representation of the message result's expected
            return type.
        argtypes:
            A list of ctypes types each of the arguments in *args must
            match. ARM64 fails if this is unspecified. Otherwise, they
            are all assumed to be c_void_p.
        **_:
            Backward compatibility with the original function signature.

    Returns:
       The result of the message, if any.

    )r9   r   rC   r?   r^   r   objc_msgSend_fpretrO   r1   extendr`   rX   POINTERobjc_msgSend_stretr   objc_msgSend)	ra   rc   rO   r`   args_selectorfull_message_arg_typesresults	            r#   send_messagerr     s   @ (C   'X&& M**H    )&*1'"
 	%%h///+A((8CdCCC 
g	&	& &G"

 	%%h///+A( fxIDIIIII
 %,!"
 	%%h///%;" "8X====hf%%FMr%   c                      e Zd ZdefdefgZdS )
OBJC_SUPERra   classN)r.   r/   r0   r1   r3   r)   r%   r#   rt   rt     s"        X&((;<HHHr%   rt   )superclass_namec                  t          | d          r| j        } |t          |           }nt          |          }t	          | |          }t          |          }|                    dt                    }|                    dd           }	|t          j	        _
        |	r!t          t          g|	z   t          j	        _        nd t          j	        _        t          j	        t          |          |g|R  }
|t          k    rt          |
          }
|
S )N_as_parameter_rO   r`   )hasattrrx   rN   rC   rt   r?   getr1   r   objc_msgSendSuperrO   OBJC_SUPER_PTRr`   r   )ra   selNamerv   rm   kwargs
superclasssuper_structro   rO   r`   rq   s              r#   
send_superr     s    x)** +*-h77

//
h
33LG$$HjjH--Gzz*d++H%,D" /+98*Dx*O''*.'#E,$7$7IDIIIF(&!!Mr%   c                   g }d}d}d}| D ]*}t          |t                    rt          |g          }|dk    r>|r1|dd         dk    r#|dk    r|dk    r|                    |           d}||z  }|dz  }l|dk    r||z  }|dz  }|dk    sJ |d	k    r>|r1|dd         dk    r#|dk    r|dk    r|                    |           d}||z  }|dz  }|d
k    r||z  }|dz  }|dk    sJ |s|r||z  }|dv r|dv r|dv r0|r|dd         dk    r||z  }|r|                    |           |},|r|                    |           |S )a  Takes a type encoding string and outputs a list of the separated type codes.
    Currently does not handle unions or bitfields and strips out any field width
    specifiers or type specifiers from the encoding.  For Python 3.2+, encoding is
    assumed to be a bytes object and not unicode.

    Examples:
    parse_type_encoding('^v16@0:8') --> ['^v', '@', ':']
    parse_type_encoding('{CGSize=dd}40@0:8{CGSize=dd}16Q32') --> ['{CGSize=dd}', '@', ':', '{CGSize=dd}', 'Q']
    r   r%      {N   ^r      }   [   ]s
   0123456789s   rnNoORVs   ^cislqCISLQfdBv*@#:b?)r9   intr6   append)encodingtype_encodingsbrace_countbracket_counttypecoder   s         r#   parse_type_encodingr   7  s!    NKMH . . a 	qc

A99 HRSSMT11kQ6F6F=\]K]K]%%h///MH1KK$YYMH1K1$$$$$$YY HRSSMT11kQ6F6F=\]K]K]%%h///MHQMM$YYMHQM!Q&&&&& 	M 	MHH-*__*** HRSSMT11A  4"))(333  (h'''r%   c                   | t           v rt           |          S i dt          dt          dt          dt          dt
          dt          dt          dt          d	t          d
t          dt          dt          dt          dd dt          dt          dt          dt          t           t"          t$          t&          t(          t*          t,          t.          t0          t2          i}g }t5          |           D ]~}||v r|                    ||                    "|dd         dk    r=|dd          |v r1|                    t9          ||dd                                        mt;          d|z             t=          | }|t           | <   |S )N   c   i   s   l   q   C   I   S   L   Q   f   d   B   v   *   @   #   :r   r   r   zunknown type encoding: )cfunctype_tablec_charc_intc_shortc_long
c_longlongc_ubytec_uintc_ushortc_ulongc_ulonglongr\   r]   c_boolr2   r1   NSPointEncodingNSPointNSSizeEncodingNSSizeNSRectEncodingNSRectNSRangeEncodingNSRangePyObjectEncoding	py_objectr   r   rj   r(   	CFUNCTYPE)r   	typecodesr`   code	cfunctypes        r#   cfunctype_for_encodingr     s    ?""x((.v .tU .D' .4 .z .w. $f..2H.>BG.MQS^.w. $h.04f.>BD.JNPX. x. "&x. 26xRYRY!9. .I H#H-- > >9OOIdO,,,,!A#Y$48y#8#8OOGId122h$78899995<===8$I
 !*OHr%   c                    t          | t                    rt          |           } t          t                              | t          |          d                    S Nr   )r9   r   rC   r1   r   objc_allocateClassPairr:   )r   r   s     r#   create_subclassr     sJ    *c"" +z**
D//
L<N<NPQRRSSSr%   c                :    t                               |            d S N)r   objc_registerClassPair)subclasss    r#   register_subclassr     s    )))))r%   c                0   t          |          }|d         dk    sJ |d         dk    sJ t          |          }t          |          } ||          }t          t          |t          gt
          j        _        t
                              | |||           |S )Nr   r      r   )r   r?   r   r1   r2   r   class_addMethodr`   )rM   r}   methodr-   r   ro   r   imps           r#   
add_methodr     s    (//N1%%%%1%%%%G$$H&u--I
)F

C%-xH$MD!hU333Jr%   c           	         t                               | t          |          t          |          t	          |          t          |                    S r   )r   class_addIvarr:   rV   	alignmentencoding_for_ctype)rM   r   vartypes      r#   add_ivarr     s?    c<#5#5vg	RYHZHZ\nov\w\wxxxr%   c                    t           t          |gt          j        _        t                              | t          |          |           d S r   )r1   r2   r   object_setInstanceVariabler`   r:   )rD   varnamer   r   s       r#   set_instance_variabler     s:    08(G/LD#,##Cg)>)>FFFFFr%   c                     |            }t                               | t          |          t          |                     |j        S r   )r   object_getInstanceVariabler:   r   r   )rD   r   r   variables       r#   get_instance_variabler     s;    wyyH##Cg)>)>hPPP>r%   c                      e Zd ZdZi dededededede	de
d	ed
edededededddddedededededeeeeeeeeeeei	Zi Zd Zd Z d Z!d Z"d Z#d Z$dS )
ObjCMethodz>This represents an unbound Objective-C method (really an IMP).r   r   r   r   r   r   r   r   r   r   r   r   r   r   Ns   Vvr   r   r   r   s   ^v   ?c           	     j    t          t                              |                     _        t                               j                   _         j                            dd           _        t                              |           _	        t          
                    |          }t          |t                    j         _        t                              |           _        t          t                              |                     _        g  _        t)           j                  D ]Z}t+          d          }t                              |||t/          |                      j                            |j                   [	  fd j        D              _        n#  d _        Y nxY w	  j        dk    rt4           _        n7 j        dk    rt8           _        n                      j                   _        n#  d _        Y nxY wd _        t>                               |           dS )zInitialize with an Objective-C Method pointer.  We then determine
        the return type and argument type information of the method.r      _i   c                :    g | ]}                     |          S r)   )ctype_for_encoding).0tselfs     r#   
<listcomp>z'ObjCMethod.__init__.<locals>.<listcomp>  s'    UUUAT44Q77UUUr%   Nr   r   )!r1   r   method_getNamero   sel_getNamer   replacepynamemethod_getTypeEncodingr   method_copyReturnTypecastr2   r   return_typemethod_getNumberOfArgumentsnargsmethod_getImplementationr   argument_typesrangec_buffermethod_getArgumentTypelenr   r`   ObjCInstancerO   	ObjCClassr   funcr   free)r   r   return_type_ptribuffers   `    r#   __init__zObjCMethod.__init__  s    !!4!4V!<!<==$$T]33	i''d3333F;;44V<<::@55f==
D99&AABB tz"" 	5 	5Ac]]F''63v;;GGG&&v|4444	!UUUUATUUUDMM	! DMMM		 4''+!T))(#66t7GHH	 DLLL			/"""""s   F% %	F04AH 	Hc                (   || j         v r| j         |         S |dd         dk    r3|dd         | j         v r"t          | j         |dd                            S |dd         dk    r|dd         t          t          fv rt          S |dd         dk    r&|dd         | j         v r| j         |dd                  S |dd         dk    r3|dd         | j         v r"t          | j         |dd                            S t          d| j        d	|          )
z3Return ctypes type for an encoded Objective-C type.r   r   r   N   rr   s   r^zunknown encoding for z: )r   rj   CGImageEncodingNSZoneEncodingr1   r(   r   )r   r   s     r#   r   zObjCMethod.ctype_for_encoding  s,   t~%%>(++ac]d""x|t~'E'E4>(122,7888ac]d""x|7X'X'XOac]d""x|t~'E'E>(122,//ac]e##(F(F4>(122,7888)TYYYQRRRr%   c                    | j         t          k    s| j         t          k    rt          t          g| j        R  | _        nt          | j         g| j        R  | _        | j        S )z*Returns a ctypes CFUNCTYPE for the method.)rO   r   r   r   r1   r`   	prototyper   s    r#   get_prototypezObjCMethod.get_prototype  s[    <<''4<9+D+D
 'x@$-@@@DNN&t|DdmDDDDN~r%   c                (    d| j         d| j        dS )Nz<ObjCMethod:  >)r   r   r  s    r#   __repr__zObjCMethod.__repr__)  s     (,			4===AAr%   c                "   | j         s|                                 }t          | j        |          | _         | j        t
          k    s| j        t          k    rt          | j         _        n| j        | j         _        | j        | j         _        | j         S )z6Returns a python-callable version of the method's IMP.)	r   r  r   r   rO   r   r   r1   r`   )r   r  s     r#   get_callablezObjCMethod.get_callable,  sv    y 	/**,,ITXy11DI||++t|y/H/H$,	!!$(L	!!%DIyr%   c           	        |                                  }	  ||| j        g|R  }| j        t          k    r<t          |          }| j                            d          r|j        du sJ d|_        n| j        t          k    rt          |          }|S # t          $ rX}|xj	        dt          | j                  z   dt          | j                  z   dt          | j                  z   fz  c_	         d}~ww xY w)zCall the method with the given id and arguments.  You do not need
        to pass in the selector as an argument since it will be automatically
        provided.)s   allocs   news   copys   mutableCopyFTzselector = z
argtypes =zencoding = N)r  ro   rO   r   r   
startswith	_retainedr   ArgumentErrorrm   r   r`   r   )r   objc_idrm   frq   errors         r#   __call__zObjCMethod.__call__8  s    	Qw5555F ||++%f--9''(STT ,!+u4444'+F$**"6**M 	 	 	JJ=3ty>>9'#dm*<*<<(3t}+=+==? ?JJ 	s   A;B 
C4AC//C4)%r.   r/   r0   __doc__c_byter   r   r   r   r   r   r   r   r   r\   r]   r   r2   r1   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r
  r  r  r)   r%   r#   r   r     sj       HH
.v .tU .D' .4 .z .w. $f..2H.>BG.MQS^.w. $h.04f.>BD.JOQU.W[]e. x. "&xxRVX` '>6>SY '!9. .I O(# (# (#VS S S$
 
 
B B B
 
 
    r%   r   c                  $    e Zd ZdZd Zd Zd ZdS )ObjCBoundMethodzThis represents an Objective-C method (an IMP) which has been bound
    to some id which will be passed as the first parameter to the method.c                "    || _         || _        dS )z>Initialize with a method and ObjCInstance or ObjCClass object.Nr   r  )r   r   r  s      r#   r   zObjCBoundMethod.__init__X  s    r%   c                2    d| j         j        d| j        dS )Nz<ObjCBoundMethod  (z)>)r   r   r  r  s    r#   r
  zObjCBoundMethod.__repr__]  s      .2k.>.>.>MMr%   c                (     | j         | j        g|R  S )z)Call the method with the given arguments.r  )r   rm   s     r#   r  zObjCBoundMethod.__call__`  s    t{4</$////r%   N)r.   r/   r0   r  r   r
  r  r)   r%   r#   r  r  T  sP        M M  
N N N0 0 0 0 0r%   r  c                  J     e Zd ZdZi Z fdZd Zd Zd Zd Z	d Z
d Z xZS )	r   z(Python wrapper for an Objective-C class.c                   t          |t                    r|}t          |          }n@|}t          |t                    st          |          }t                              |          }|| j        v r| j        |         S t          t          |           	                    |           }||_
        ||_        i |_        i |_        ||_        || j        |<   |                                 |                                 |S )zCreate a new ObjCClass instance or return a previously created
        instance for the given Objective-C class.  The argument may be either
        the name of the class to retrieve, or a pointer to the class.)r9   r   rC   r1   r   class_getName_registered_classessuperr   __new__ptrr   instance_methodsclass_methodsrx   cache_instance_methodscache_class_methods)rM   class_name_or_ptrr   r$  
objc_class	__class__s        r#   r#  zObjCClass.__new__q  s    
 '-- 		+$DD//CC#C c8,, $smm%%c**D 3****400 9c**22377


&(
##%
 $'
! )3% 	))+++&&(((r%   c                L    d| j         dt          | j        j                  dS )Nz<ObjCClass: z at r	  )r   r   r$  r   r  s    r#   r
  zObjCClass.__repr__  s'     *.)))S5H5H5H5HIIr%   c                D   t                      }t                              | j        t	          |                    }t          |j                  D ]5}t          ||                   }t          |          }|| j	        |j
        <   6t                              |           dS )zCreate and store python representations of all instance methods
        implemented by this class (but does not find methods of superclass).N)r   r   class_copyMethodListr$  r   r   r   r1   r   r%  r   r   r   r   countmethod_arrayr   r   objc_methods         r#   r'  z ObjCClass.cache_instance_methods  s     005<<HHu{## 	D 	DAl1o..F$V,,K8CD!+"455		,r%   c                t   t                      }t                              t                              | j                  t          |                    }t          |j                  D ]5}t          ||                   }t          |          }|| j
        |j        <   6t                              |           dS )zCreate and store python representations of all class methods
        implemented by this class (but does not find methods of superclass).N)r   r   r.  rF   r$  r   r   r   r1   r   r&  r   r   r   r/  s         r#   r(  zObjCClass.cache_class_methods  s     001E1Edh1O1OQVW\Q]Q]^^u{## 	A 	AAl1o..F$V,,K5@D{122		,r%   c                   || j         v r| j         |         S t          |                    dd                    }t          t                              | j        |                    }|j        rt          |          }|| j         |<   |S dS )zReturns a python representation of the named instance method,
        either by looking it up in the cached list of methods or by searching
        for and creating a new method object.r   r   N)	r%  r?   r   r1   r   class_getInstanceMethodr$  r   r   r   r   ro   r   r2  s        r#   get_instance_methodzObjCClass.get_instance_method  s     4((((.. $DLLt$<$<==Hd::48XNNOOF| #(00.9%d+""tr%   c                   || j         v r| j         |         S t          |                    dd                    }t          t                              | j        |                    }|j        rt          |          }|| j         |<   |S dS )zReturns a python representation of the named class method,
        either by looking it up in the cached list of methods or by searching
        for and creating a new method object.r   r   N)	r&  r?   r   r1   r   class_getClassMethodr$  r   r   r6  s        r#   get_class_methodzObjCClass.get_class_method  s     4%%%%d++ $DLLt$<$<==Hd77(KKLLF| #(00+6"4(""tr%   c                    t          |          }|                     |          }|rt          || j                  S |                     |          }|r|S t          d| j        d|          )z5Returns a callable method object with the given name.z
ObjCClass z has no attribute )r:   r:  r  r$  r7  AttributeErrorr   )r   r   r   s      r#   __getattr__zObjCClass.__getattr__  s     D!!&&t,, 	5"648444 ))$// 	M n4999ddSTTTr%   )r.   r/   r0   r  r!  r#  r
  r'  r(  r7  r:  r=  __classcell__r+  s   @r#   r   r   g  s        22 $ $ $ $ $LJ J J     
  
  
   "  "U U U U U U Ur%   r   c                  6    e Zd Zd Zed             Zd Zd ZdS )_AutoreleasepoolManagerc                $    d| _         d g| _        d S r   )currentpoolsr  s    r#   r   z _AutoreleasepoolManager.__init__  s    V


r%   c                0    t          | j                  dz
  S )z,Number of total pools. Not including global.r   )r   rD  r  s    r#   r0  z_AutoreleasepoolManager.count  s     4:""r%   c                x    | j                             |           | j                             |          | _        d S r   )rD  r   indexrC  r   pools     r#   createz_AutoreleasepoolManager.create  s3    
$z''--r%   c                r    | j                             |           t          | j                   dz
  | _        d S )Nr   )rD  remover   rC  rH  s     r#   deletez_AutoreleasepoolManager.delete  s0    
$4:*r%   N)r.   r/   r0   r   propertyr0  rJ  rM  r)   r%   r#   rA  rA    s\           # # X#. . .+ + + + +r%   rA  c                  r     e Zd ZdZdZdZ ej                    Zd fdZ	d Z
dd	Zd
 ZddZd Zd Z xZS )r   z+Python wrapper for an Objective-C instance.r   F
object_ptrr   c                   t          |t                    st          |          }|j        sdS |j        | j        v r| j        |j                 S t	          t
          |                               |           }||_        ||_        t          t          
                    |                    }t          |          |_        || j        |j        <   |S )zCreate a new ObjCInstance or return a previously created one
        for the given object_ptr which should be an Objective-C id.N)r9   r1   r   _cached_objectsr"  r   r#  r$  rx   r   rF   r   r*  )rM   rP  objc_instance	class_ptrr+  s       r#   r#  zObjCInstance.__new__  s     *h// 	.!*--J  	4 s222&z'788 lC0088==&'1$T11*==>>	#,Y#7#7  1>J,-r%   c                4    d| _         t          | d           d S )NFreleaser  rr   r  s    r#   rV  zObjCInstance.release&  s    T9%%%%%r%   r   c                N    d| _         t          | d          }t          |          S )a	  Release when object when the current pool is popped.

        Normally doesn't need to be called because the AutoReleasePool manager will do it automatically, which saves
        a lot of boilerplate.

        However, can be useful for debugging purposes.
        Fautorelease)r  rr   r   )r   r$  s     r#   rY  zObjCInstance.autorelease*  s(     4//C   r%   c                8    | j         rt          | d           dS dS )zInstance was deleted either manually or through garbage collection.

        If we are retaining an allocation, release it.
        rV  NrW  r  s    r#   __del__zObjCInstance.__del__6  s.    
 > 	*y)))))	* 	*r%   r   r   rD   r
   c                (    t          | ||           dS )zAssociate a Python object to the Objective-C instance with the given name.

        By associating python data with the instance, we end up keeping the instance from GCing on Pythons side until
        all associates are removed.
        N)_set_dealloc_observer)r   r   rD   s      r#   	associatezObjCInstance.associate>  s     	dD#.....r%   c                   | j         j        dk    rHddlm}  ||           }dt	          |           | j         j        |t          | j        j                  fz  S dt	          |           | j         j        t          | j        j                  fz  S )Ns
   NSCFStringr   )cfstring_to_stringz!<ObjCInstance %#x: %s (%s) at %s>z<ObjCInstance %#x: %s at %s>)r*  r   	cocoalibsr`  idr   r$  r   )r   r`  strings      r#   r
  zObjCInstance.__repr__F  s    ?=00555555''--F6"T((DODXZ`befjfnftbubu9vvv-D4?;OQTUYU]UcQdQd0eeer%   c                   t          |          }| j                            |          }|rt          ||           S | j                            |          }|rt          || j        j                  S t          |          }t                              | |          }|.d| j        j	         d| j        j
         d| }t          |          t          |dt                    }t          |t                    }|j
        S )zReturns a callable method object with the given name.

        This is only called when the name doesn't exist in __dict__.
        NzObjCInstance r  z) has no attribute observed_object)r:   r*  r7  r  r:  r$  _assigned_internal_namer   objc_getAssociatedObjectr   r   r<  r   r1   r   r   )	r   r   r    r   internal_nameobservermsgaddresspy_ptrs	            r#   r=  zObjCInstance.__getattr__O  s     "$''
44Z@@ 	1"64000 11*== 	@"64?+>??? 05500}EEc$/"6cc$(.cc]accC %%%'2CXNNgy))|r%   )rP  r   )r   r   )r   r   rD   r
   )r.   r/   r0   r  rI  r  weakrefWeakValueDictionaryrR  r#  rV  rY  r[  r^  r
  r=  r>  r?  s   @r#   r   r     s        55DI1g133O     @& & &
! 
! 
! 
!* * */ / / /f f f             r%   r   c                 R    d t           j                                        D             S )zfFor debug purposes, return a list of instance names.
    Useful for debugging if an object is leaking.c                B    g | ]}|j         j        |j        |j        |fS r)   )r*  r   r  rI  )r   rD   s     r#   r   z(get_cached_instances.<locals>.<listcomp>u  s*    qqqCS^ #-3?qqqr%   )r   rR  valuesr)   r%   r#   get_cached_instancesrr  r  s(     rq<KgKnKnKpKpqqqqr%   c                2   g }t          |           dd         }t          ||          D ]l\  }}|dk    r#|                    t          |                     .|dk    r#|                    t	          |                     W|                    |           m|S )zUsed by ObjCSubclass to convert Objective-C method arguments to
    Python values before passing them on to the Python-defined method.   Nr   r   )r   zipr   r   r   )r   rm   new_argsarg_encodingseas         r#   convert_method_argumentsrz  x  s     H'11!""5MM4((  199OOLOO,,,,$YYOOIaLL))))OOAOr%   c                  D    e Zd ZdZddZd Zd Zd Zd Zd Z	d	 Z
d
 ZdS )ObjCSubclasszUse this to create a subclass of an existing Objective-C class.
    It consists primarily of function decorators which you use to add methods
    to the subclass.Tc                    i | _         || _        t          ||          | _        | j        | _        |r|                                  d S d S r   )
_imp_tabler   r   objc_clsrx   register)r   r   r   r  s       r#   r   zObjCSubclass.__init__  sN    	'
D99"m 	MMOOOOO	 	r%   c                v    t                               | j                   t          | j                  | _        dS )z4Register the new class with the Objective-C runtime.N)r   r   r  rJ   r   objc_metaclassr  s    r#   r  zObjCSubclass.register  s0    ##DM222+DI66r%   c                .    t          | j        ||          S )zAdd instance variable named varname to the subclass.
        varname should be a string.
        vartype is a ctypes type.
        The class must be registered AFTER adding instance variables.)r   r  )r   r   r   s      r#   r   zObjCSubclass.add_ivar  s    
 w888r%   c                H    t          | j        |||          }|| j        |<   d S r   )r   r  r~  r   r   r   r   r   s        r#   r   zObjCSubclass.add_method  s)    fh?? #r%   c                H    t          | j        |||          }|| j        |<   d S r   )r   r  r~  r  s        r#   add_class_methodzObjCSubclass.add_class_method  s*    ,dFHEE #r%   c                     t                    t                    }|                    dd           d                    |           fd}|S )zDecorator for instance methods without any fancy shenanigans.
        The function must have the signature f(self, cmd, *args)
        where both self and cmd are just pointers to objc objects.r      @:r%   c                l    | j                             dd          }                    | |           | S )Nrn   :r.   r   r   )r  r   r   r   s     r#   	decoratorz)ObjCSubclass.rawmethod.<locals>.decorator  s5    :%%c3//DOOAtX...Hr%   r:   r   insertjoinr   r   r   r  s   ``  r#   	rawmethodzObjCSubclass.rawmethod  sm    
  ))'11	E"""88I&&	 	 	 	 	 	
 r%   c                     t                    t                    }|                    dd           d                    |           fd}|S )z(Function decorator for instance methods.r   r  r%   c                z      fd} j                             dd          }                    ||           |S )Nc                    t          |           }t          |          } |g|R  }t          |t                    r|j        j        }n!t          |t                     r|j        j        }|S r   )r   rz  r9   r   r$  r   )	objc_selfobjc_cmdrm   py_selfrq   r   r  s        r#   r2  z;ObjCSubclass.method.<locals>.decorator.<locals>.objc_method  su    &y11/$??7*T***fi00 .#Z-FF55 .#Z-Fr%   rn   r  r  )r  r2  r   r   r   s   `  r#   r  z&ObjCSubclass.method.<locals>.decorator  sW          :%%c3//DOOKx888r%   r  r  s   ``  r#   r   zObjCSubclass.method  sm      ))'11	E"""88I&&	 	 	 	 	 	 r%   c                     t                    t                    }|                    dd           d                    |           fd}|S )z%Function decorator for class methods.r   r  r%   c                z      fd} j                             dd          }                    ||           |S )Nc                    t          |           }t          |          } |g|R  }t          |t                     r|j        j        }n!t          |t
                    r|j        j        }|S r   )r   rz  r9   r$  r   r   )r  r  rm   py_clsrq   r   r  s        r#   objc_class_methodzFObjCSubclass.classmethod.<locals>.decorator.<locals>.objc_class_method  su    "8,,/$??6)D)))fi00 .#Z-FF55 .#Z-Fr%   rn   r  )r.   r   r  )r  r  r   r   r   s   `  r#   r  z+ObjCSubclass.classmethod.<locals>.decorator  sZ          :%%c3//D!!"3T8DDD$$r%   r  r  s   ``  r#   classmethodzObjCSubclass.classmethod  sm      ))'11	E"""88I&&	% 	% 	% 	% 	% 	% r%   N)T)r.   r/   r0   r  r   r  r   r   r  r  r   r  r)   r%   r#   r|  r|    s            7 7 79 9 9$ $ $
$ $ $  "  2    r%   r|  c                  2   e Zd Z eddd          Ze                    de           e                                 e                    d          d             Z	e                    d          d	             Z
e                    d          d
             ZdS )#DeallocationObserver_ImplementationNSObjectDeallocationObserverF)r  re  z@@c                    t          | d          } | Bt          |t                    }|j        t          | j        |f<   t          | d|t                     | j        S )Ninitre  )r   r   r   r   _python_objectsr   r1   )r   cmdobjc_ptrpy_objs       r#   initWithObjectId_z5DeallocationObserver_Implementation.initWithObjectId_:  sV    $''(I..F6<lOTZ23!$(98XNNNzr%   vc                j    t          | dt                    x}r
t          | |f= t          | d           d S )Nre  dealloc)r   r1   r  r   r   r  r  s      r#   r  z+DeallocationObserver_Implementation.deallocC  s?    ,T3DhOOO8 	2x 014#####r%   c                t    t          | dt                    x}rt          | |j        f= t	          | d           d S )Nre  finalize)r   r1   r  r   r   r  s      r#   r  z,DeallocationObserver_Implementation.finalizeJ  sC     -T3DhOOO8 	8x~ 674$$$$$r%   N)r.   r/   r0   r|  r  r   r1   r  r  r  r  r  r)   r%   r#   r  r  5  s        '<
4JUZ[[[!!"3X>>>!!#####D))  *) ##C(($ $ )($ ##C((	% 	% )(	% 	% 	%r%   r  c                    t          | dt                    }|rBt                              || dt                     t
          j                            |d           t          | |           dS )zRemoves any cached ObjCInstances in Python to prevent memory leaks.
    Manually break association as it's not implicitly mentioned that dealloc would break an association,
    although we do not use the object after.
    re  N)	r   r1   r   objc_setAssociatedObjectOBJC_ASSOCIATION_ASSIGNr   rR  popr   )objc_obsrc   r  s      r#   _obj_observer_deallocr  V  sh    
 %X/@(KKH 9%%h$@WXXX$((4888x'''''r%   c                *    d|  }t          |          S )Nz_internal.assign.)r?   )r   keys     r#   rf  rf  b  s    
$d
$
$Cr%   c                    t          dd          }t          |dt          |          t                    }t                              | t          |          |t                     t          |d           |S )Nr  alloczinitWithObjectId:)r`   rV  )rr   rb  _dealloc_argtyper   r  rf  OBJC_ASSOCIATION_RETAIN)r   r   
python_objri  s       r#   r]  r]  f  sm    
 2G<<HH&92j>>TdeeeH!!$(?(E(ExQhiii
 9%%%Or%   c                X    | j         }t                              | |d t                     d S r   )	_observerr   r  r  )r  ri  s     r#   _remove_dealloc_observerr  w  s+    !H!!(Hd<STTTTTr%   c               #     K   t                                           } 	 dV  t                               |            dS # t                               |            w xY w)a<  Use objc_autoreleasePoolPush/Pop because NSAutoreleasePool is no longer recommended:
        https://developer.apple.com/documentation/foundation/nsautoreleasepool
    @autoreleasepool blocks are compiled into the below function calls behind the scenes.
    Call them directly to mimic the Objective-C behavior.
    N)r   objc_autoreleasePoolPushobjc_autoreleasePoolPop)rI  s    r#   AutoReleasePoolr  |  s[       ((**D+$$T*****$$T****s	   = A)r   r   r   r   )r   r   )r4   r5   r   r6   )r   r;   r   r1   )r   r5   r   r@   )rD   r1   r   r@   )r   r;   r   r@   )rO   r   r   rP   )
ra   rb   rc   r;   rO   rd   r`   re   r   rf   )r   r   )
__future__r   sysplatformstructrm  
contextlibr   ctypesr   typingr   r   r	   r
   
cocoatypescalcsizerU   machinerZ   	__arm64__rV   r1   c_int32c_ptrdiff_tc_int64find_librarylibcdllLoadLibraryr   r   r   rO   r`   r2   rj   r   r   r   r$   r*   r   r   c_uint8r   class_addProtocolclass_conformsToProtocolclass_copyIvarListr   r.  class_copyPropertyListclass_copyProtocolListclass_createInstancer9  class_getClassVariabler5  class_getInstanceSizeclass_getInstanceVariableclass_getIvarLayoutclass_getMethodImplementation#class_getMethodImplementation_stretr   class_getPropertyrL   class_getVersionclass_getWeakIvarLayoutclass_isMetaClassclass_replaceMethodclass_respondsToSelectorclass_setIvarLayoutclass_setSuperclassclass_setVersionclass_setWeakIvarLayoutivar_getNameivar_getOffsetivar_getTypeEncodingmethod_copyArgumentTyper   r   method_exchangeImplementationsr   r   r   r   method_getReturnTyper   method_setImplementationr   objc_copyProtocolListrg  rB   objc_getClassListrI   objc_getProtocolobjc_msgSendSuper_stretrk   r   objc_removeAssociatedObjectsr  object_copyobject_disposerF   object_getClassNamer   object_getIvarobject_setClassr   object_setIvarproperty_getAttributesproperty_getNameprotocol_conformsToProtocolrT   r,   "protocol_copyMethodDescriptionListprotocol_copyPropertyListprotocol_copyProtocolListprotocol_getMethodDescriptionprotocol_getNamer   sel_isEqualr=   r  r  r  r  OBJC_ASSOCIATION_COPYr:   r?   rC   rG   rJ   rN   rX   r^   r_   rr   rt   r|   r   r   r   r   r   r   r   r   r   r   r   r  r   rA  _arp_managerr   rr  rz  r|  r  r  r  r  rf  r]  r  r  r)   r%   r#   <module>r
     s  > # " " " " " 



    % % % % % %           / / / / / / / / / / / /    $$$*H&(X7*		6(qKKVHK d ;
"C))#..// 	 Z	 &''(2C2CXxX  !  	% 	% 	% 	%   " $  '8WhO    &   "(  #+X"6   )/  %*2H)=  & #*'("3"3  $,ggfoo#>    %,GH$5$5  !&.%@  " '.gh&7&7  #(0''&//'B  $ '.gh&7&7  #(0''&//'B  $ %-  !&.%9  " %-  !&.%9  " '/  #(0(';  $ (0  $)18(<  % &.  "'/j  # *2  &+3X*>  ' $,   %-J  ! .6 " */7.B " +  M7?D,49A88LD,5 &  'j   "*  #+X"6   $,   %-J  ! !&  "*   (0  $)1
  % "(  #+*   $,   %-x8$L  ! )/  %*2H)=  & $(   %-x$8  ! $,   %-x$8  ! !%  "*E!2   (,  $)18(<  %
 %  &Z   *   (z   %-  !&.Z  " (0  $)16(:  % &-WV__  "'/j  # /3 # +08(/C # , '+  #(0&(H'M  $ )1  %*2  & '   (z   ,2   (-5J   ) %)  !&.(%C  " '/  #(0z  $ )1  %*2H)=  &
 '/  #(0(H'E  $
 &-WX%6%6  "'.wu~~&6  # )1  %*2H)=  & &  'j   "'  #+U"3   "*  #+*   !)  "*    0+/D (  +&*D# '+  #(0z  $ -1 ! ).6Z ! * )-  %*2Hh)N  &
 $  %x0   '   (z    (  !)
   $,   %-J  ! +3  ',4h+I  ( '   ((3    (  !)8 4   +3  ' #   ((H=  
 '/  #(0z  $ !)  "*  
 ,2   (-5x,@   )9 9 9 9 9i 9 9 9 3:':Q2R2R ' /4<ffggV\oo3^ ' 0 *2  &+3WWV__*E  ' ")!2!2 +3WWV__*E  ' .E " */766.R " + !)  "*  
 $  %J   "  %x0   !)  "*  
 )1  %)+  & (,  $)1
  %        ,? ? ? ? < < < <(/ / / / @ @ @ @03 3 3 3*% % % %P   F )** )1*.u u u u u up= = = = = = = = $$ :>     0 B B BP  JT T T* * *	 	 	y y yG G G
         H0 0 0 0 0 0 0 0&}U }U }U }U }U }U }U }UF+ + + + + + + +& '&((p p p p p p p pfr r r  Fd d d d d d d dR :  % % % % % % % %B
( 
( 
(     "U U U
 + + + + +r%   