
    e|                     R   d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddl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 ddlmZmZ ddlmZ dd	lmZ ej4                  d6d
       Zdad Z G d de      Zd Z d7dZ!d8dZ"d8dZ#d9dZ$d9dZ%d Z&d:dZ'd;dZ(d Z)d Z*d<dZ+ G d de      Z, G d de      Z-d=dZ.d>dZ/d  Z0d6d!Z1 G d" d#e      Z2d?d$Z3d% Z4d& Z5d' Z6d( Z7d) Z8d@d*Z9i Z:dAd+Z; G d, d-e      Z<d. Z=dBd/Z> G d0 d1e      Z?d6d2Z@ G d3 d4e      ZAd5 ZBy)Cz
debug.py - Functions to aid in debugging 
Copyright 2010  Luke Campagnola
Distributed under MIT/X11 license. See license.txt for more information.
    )print_functionN)perf_counter)ndarray   )QT_LIBQtCore)cprint)Mutexc              #      K   | t         j                  nt        | dd      }	 | |t         j                  ur|j                          y y # |t         j                  ur|j                          w w xY ww)Nwzutf-8)encoding)sysstdoutopenclose)filenamefhs     1/usr/lib/python3/dist-packages/pyqtgraph/debug.pyopen_maybe_consoler   !   s]     'T(C'-RBSZZHHJ  2SZZHHJ  s   !A4A $A4%A11A4c                       fd}|S )zpDecorator used for marking the beginning and end of function calls.
    Automatically indents nested calls.
    c                      dt         z  }t        |j                  z   dz          t         dz  a 	  | i |}t         dz  a t        |j                  z   dz          |S # t         dz  a w xY w)N  z startr   z done)__ftraceDepthprint__name__)argskargspfxrvfuncs       r   r   zftrace.<locals>.w0   st    ]"cDMM!H,-	t%u%BQMcDMM!G+,	 QMs   A A) r    r   s   ` r   ftracer#   ,   s    
 H    c                   .    e Zd ZdZd Zd Zd Zd Zd Zy)TracerzS
    Prints every function enter/exit. Useful for debugging crashes / lockups.
    c                      d| _         g | _        y )Nr   )countstackselfs    r   __init__zTracer.__init__B   s    

r$   c                 j   | xj                   dz  c_         | j                   dz  dk(  r't        d       | j                  D ]  }t        |        |dk(  r_dt        | j                        z  dz   | j	                  |      z   }t        |       | j                  j                  |       | j                  S |dk(  rq| j                  j                          dt        | j                        z  d	z   | j	                  |      z   }t        |       t        | j                        dk(  rd| _         | j                  S )
Nr     r   z----- current stack: -----callr   z>> returnz<< )r(   r   r)   len	frameInfoappendpoptrace)r+   frameeventarglines        r   r5   zTracer.traceF   s    

a
 ::!./

 dF?#djj/)E1DNN54IID$KJJd# zz hJJNN#djj/)E1DNN54IID$K4::!#
zzr$   c                 .    t        j                  d        y N)r   settracer*   s    r   stopzTracer.stop[   s    Tr$   c                 B    t        j                  | j                         y r;   )r   r<   r5   r*   s    r   startzTracer.start^   s    TZZ r$   c                    |j                   j                  }|j                   j                  }|j                  }t	        j
                  d      }d|j                   j                  |j                  fz  }t        j                  |      \  }}}}	t        |      r=|d   dk(  r5|	j                  dd       }
|
!t        |
dd       }||j                  dz   |z   }|d|d|d|S )	N   z%s %dr   r+   	__class__.z:  )f_codeco_filenameco_namef_linenor   	_getframeinspectgetargvaluesr1   getgetattrr   )r+   frr   funcnamelinenocallfrcallliner   _
value_dictinstanceclss               r   r2   zTracer.frameInfoa   s    99((99$$q!fmm33V__EE!(!5!5b!9aJt9aF*!~~fd3H#hT:?"||c1H<H"*HfhGGr$   N)	r   
__module____qualname____doc__r,   r5   r=   r?   r2   r!   r$   r   r&   r&   >   s!    *!Hr$   r&   c                       fd}|S )zCDecorator that catches/ignores exceptions and prints a stack trace.c                  <    	  | i | y #  t        d       Y y xY w)NzIgnored exception:)printExc)r   kwdsr    s     r   r   zwarnOnException.<locals>.ws   s%    	+$$	+)*s    r!   r"   s   ` r   warnOnExceptionr^   q   s    +
 Hr$   c                    t        t        j                         d|i}g }|D ]1  }|j                  |j	                  d      j                  d             3 |D cg c]  }d| z  |z   |z    }}dj                  |      S c c}w )Nskip
rD   )formatExceptionr   exc_infoextendstripsplitjoin)indentprefixr`   lineslines2llines3s          r   getExcrn   {   s    S\\^7$7EF 1aggdm))$/01/56!c&j6!A%6F699V 7s   A?c                 z    t        ddd      }t        j                  dj                  | |g      t        d       y)zPrint an error message followed by an indented exception backtrace
    (This function is intended to be called within except: blocks)r       )rh   ri   r`   ra   )
stacklevelN)rn   warningswarnrg   RuntimeWarning)msgrh   ri   excs       r   r\   r\      s/     "1
-CMM$))S#J'AFr$   c                    t        d      }t        dt        j                  d      d| d       t        d|z  |z   dz   dz          |j	                  d      D ]  }t        d|z  |z   dz   |z           t        d|z  |z   dz   d	z          y
)z:Print an error message followed by an indented stack tracer   [z%H:%M:%Sz]  ra   rD   z==============================z>>z<<N)	backtracer   timestrftimerf   )rv   rh   ri   r5   r9   s        r   
printTracer}      s    aLE	$--
3S
9:	#f*v

&
-.D! 0c&j6!C'$./0	#f*v

&
-.r$   c                 V    dj                  t        j                         d | dz           S )Nrp   r   )rg   	tracebackformat_stackr`   s    r   rz   rz      s'    779))+JtAvY788r$   c                     t        j                  | ||      }|d   gt        j                         d|dz     z   dgz   |dd z   }|S )ay  Return a list of formatted exception strings.
    
    Similar to traceback.format_exception, but displays the entire stack trace
    rather than just the portion downstream of the point where the exception is
    caught. In particular, unhandled exceptions that occur during Qt signal
    handling do not usually show the portion of the stack that emitted the
    signal.
    r   Nr   z   --- exception caught here ---
)r   format_exceptionr   )exctypevaluetbr`   rj   s        r   rb   rb      s[     &&wr:E1XJ//1*T!V9==Ad@eehmnonphqqELr$   c           
      R    t        dj                  t        | ||d                   y)zPrint an exception with its full traceback.
    
    Set `sys.excepthook = printException` to ensure that exceptions caught
    inside Qt signal handlers are printed with their full stack trace.
    rp   r   r   N)r   rg   rb   )r   r   r   s      r   printExceptionr      s      
"''/'5)!D
EFr$   c           	         |/t        j                         D cg c]  }t        ||      s| c}S t        j                         D cg c].  }t        j                  | t        |      j                        s-|0 c}S c c}w c c}w )zjList all objects managed by python gc with class name matching regex.
    Finds 'Q...' classes by default.)gcget_objects
isinstancerematchtyper   )regextypxs      r   listObjsr      sb     >>+Baz!S/ABB>>+QarxxtAw?O?O/PQQ CQs   A>A>.B7Bc           	        	 g }||g}|i }|i }d|t        t        j                               <   d|t        |      <   d|t        |      <   dd|z
  z  }|dz  }|r|j                          t	        j
                          t	        j                  |      D 	cg c]  }	t        |	      |vs|	 }
}	d|t        |
      <   |
D ]  	t        	      j                  dv r	 t        	fd|D              r2	 	| u r+|j                  	g       t        t        | g|z                b|dk(  rhd}	 |t        	         }|d   |k\  r#|d   }|D ]  }t        t        ||z                 d|t        |      <   |(t        | 	|dz
  d	g|z   |	      }||g|t        	      <   t        |      dk(  r|D ]  }|j                  |	gz           	 |S c c}	w #  t        	       t        |        xY w# t        $ r Y w xY w)
z@Determine all paths of object references from startObj to endObjNrD      )r6   functionlistiteratorc              3   &   K   | ]  }|u  
 y wr;   r!   ).0r   rs     r   	<genexpr>zfindRefPath.<locals>.<genexpr>   s     )a16)   r   r   F)restartpathignore)idr   rI   clearr   collectget_referrersr   r   anyr   r3   refPathStringKeyErrorfindRefPathr1   )startObjendObjmaxLenr   seenr   r   refsri   r   newRefstreecacheps            `    r   r   r      s1   D|x~|"&F2cmmoF2d8F2d8!F(^F
cMF

JJL**62JQbe66IqJGJF2g;  *#7DD	)D)) * =KK-
401Q; 	AKEQx6!Qx 1A-$/01
  r$x<xF1He1#d([abD!4.DAKt9> #AqcE"#S*#X Ko K(	!H$K"  		s*   G*GG+9G-G*-	G98G9c                    	 t        |       t        t        fv rt        |       S t	        | t
              rgt        |       dkD  r.ddj                  t        | j                               dd       z  S ddj                  t        | j                                     z  S t	        | t              rt        |       dkD  rd| dd z  S | dd S t	        | t              r/dt        | j                        d	t        | j                        d
S t        | d      rt        |       dkD  rOdt        |       j                  ddj                  | dd D cg c]  }t        |      j                   c}      dS dt        |       j                  ddj                  | D cg c]  }t        |      j                   c}      dS dt        |       j                  d	| j                  j                  d
S c c}w c c}w #  t        t        |             cY S xY w)z4Return a short but descriptive string for any object   z<dict {%s,...}>,Nz<dict {%s}>2   z"%s..."z	<ndarray rD   >__len__<z [z,...]>z]>)r   intfloatstrr   dictr1   rg   listkeysr   dtypeshapehasattrr   rB   )objos     r   	objStringr   
  s   9e$s8OT"3x!|(CHHT#((*5Ebq5I,JKK$chhj1A(BCCS!3x"} 3s8++1vW%(+CIICIIGGS)$3x!|*.s)*<*<chhbefhghbiGj]^QHXHXGj>kll  '+3i&8&8#((^aCbYZDGDTDTCb:cdd	 % !%S	 2 2CMM4J4JKK	 HkCb49~sZ   !G4 AG4 0*G4 %G4 G4 >G4 AG4 G*$	G4 .&G4 G/0	G4 :/G4 *
G4 4Hc                    t        | d         }d}|t        |       dz
  k  rF|dz  }| |dz
     }| |   d}t        |t              st        |t              r,t        fd|D              r|d|j                        z  z  }rt        t              rRt        |d      rF|j                  k(  r7|dz  }|t        |       k\  r|dz  }| |   }D ]  }|   |u s|d|z  z  }d	} t        |t              r:	 |v r|d
t              z  z  }	 |D ]  }||   u s|dt        |      z  z  }d	} |r"|dz  }t        j                  j                          |t        |       dz
  k  rF|S # t        $ r Y iw xY w)zGiven a list of adjacent objects in a reference path, print the 'natural' path
    names (ie, attribute names, keys, and indexes) that follow from one object to the next .r   r   Fc              3   &   K   | ]  }|u  
 y wr;   r!   )r   r   o2s     r   r   z refPathString.<locals>.<genexpr>1  s     'q27'r   z[%d]__dict__z	.__dict__z.%sTz[key:%s]z[%s]z ? )r   r1   r   r   tupler   indexr   r   r   	TypeErrorr   r   flush)chainsio1conto3kr   s          @r   r   r   %  s    	%(A	A
c%jl
	Q1Q3Z1Xb$:b%#8'B''Vbhhrl**b$GB
$;bkk@QFACJ[ qB a5B;NAD	 b$8im33A 
  a5B;)A,..AD	 	U


[ c%jl
\ H%  s   7E, ,	E87E8c                 ,   g d}|D cg c]#  }t        t        |      st        t        |      % }}t        j                  d      }|i }d|z  }	 t        |        | }	|	|v ryd||	<   	 t        j                  |       }
t        | t              r	 |
t        | j                        z  }
|rt        |       t         t"        fv r@|rt%        |dz          | D ]*  }t'        ||||dz         }|rt%        |d	z   |       |
|z  }
, nSt        | t(              rC|rt%        |dz          | D ].  }t'        | |   |||dz         }|rt%        |d	z   ||       |
|z  }
0 t+        j,                          |rt%        |d
z          t/        |       D ]  }|dv rt        | |      }t        |      |v r"t        t        |            }|j1                  |      rHt+        j2                  |      D cg c]!  }t        |      t        j4                  k7  s |# }}t        |      dk(  st'        ||||dz         }|
|z  }
|st%        |d	z   ||        |
S c c}w #  dt        t        |             t        |       fz  }	Y xY w# t        $ r d}
Y w xY w#  Y xY wc c}w )z(Guess how much memory an object is using)
MethodTypeUnboundMethodTypeBuiltinMethodTypeFunctionTypeBuiltinFunctionTypez,(method-wrapper|Flag|ItemChange|Option|Mode)r   z%s:%dr   r   zlist:)r   verbosedepthz  +zattrs:)r   )r   typesrM   r   compilehashr   r   r   r   	getsizeofr   r   r   r1   datar   r   r   
objectSizer   r   r   dirsearchr   	FrameType)r   r   r   r   	recursiveignoreTypeskeyignoreRegexrh   hshsizer   r   r   strtypr   r   s                    r   r   r   [  s   qK2=U3PSAT75#&UKU**KLK ~%ZF2S	 f}F3K}}S! #w	CM!D
 9u%fWn% qaP&,*		
 T"fWn% s1vfgUSTWU&,1-		& 	

&/"S 	0AL QAAw+%a\F!!&)  "//2Q!d1g6PAQDQ4yA~qaP	&5.!Q/'	0. Kq V2T#YC11  	f Rs@   III *I7 J	 #!JJ$I47JJ	Jc                   .    e Zd ZdZd Zd Zd Zd Zd Zy)GarbageWatchera  
    Convenient dictionary for holding weak references to objects.
    Mainly used to check whether the objects have been collect yet or not.
    
    Example:
        gw = GarbageWatcher()
        gw['objName'] = obj
        gw['objName2'] = obj2
        gw.check()  
        
    
    c                 D    t        j                         | _        g | _        y r;   )weakrefWeakValueDictionaryobjsallNamesr*   s    r   r,   zGarbageWatcher.__init__  s    //1	r$   c                 X    || j                   |<   | j                  j                  |       y r;   )r   r   r3   )r+   r   names      r   addzGarbageWatcher.add  s!    		$T"r$   c                 (    | j                  ||       y r;   )r   )r+   r   r   s      r   __setitem__zGarbageWatcher.__setitem__  s    dr$   c                     t        j                          | j                  dd }g }| j                  D ]$  }|j	                  |       |j                  |       & t        d|       t        d|       y)zIPrint a list of all watched objects and whether they have been collected.NzDeleted objects:zLive objects:)r   r   r   r   remover3   r   )r+   deadaliver   s       r   checkzGarbageWatcher.check  s^    


}}Q 	AKKNLLO	 	 $'ou%r$   c                      | j                   |   S r;   )r   )r+   items     r   __getitem__zGarbageWatcher.__getitem__  s    yyr$   N)	r   rW   rX   rY   r,   r   r   r   r   r!   r$   r   r   r     s     #	&r$   r   c                        e Zd ZdZej
                  j                  dd      Zeej                  d      ng ZdZ	g Z
dZ G d de      Z e       Zd fd		Zdd
ZddZd Zd ZddZd Z xZS )Profilera  Simple profiler allowing measurement of multiple time intervals.

    By default, profilers are disabled.  To enable profiling, set the
    environment variable `PYQTGRAPHPROFILE` to a comma-separated list of
    fully-qualified names of profiled functions.

    Calling a profiler registers a message (defaulting to an increasing
    counter) that contains the time elapsed since the last call.  When the
    profiler is about to be garbage-collected, the messages are passed to the
    outer profiler if one is running, or printed to stdout otherwise.

    If `delayed` is set to False, messages are immediately printed instead.

    Example:
        def function(...):
            profiler = Profiler()
            ... do stuff ...
            profiler('did stuff')
            ... do other stuff ...
            profiler('did other stuff')
            # profiler is garbage-collected and flushed at function end

    If this function is a method of class C, setting `PYQTGRAPHPROFILE` to
    "C.function" (without the module name) will enable this profiler.

    For regular functions, use the qualified name of the function, stripping
    only the initial "pyqtgraph." prefix from the module.
    PYQTGRAPHPROFILENr   r   Fc                   &    e Zd Zd Zd Zd ZddZy)Profiler.DisabledProfilerc                      y r;   r!   )r+   r   r]   s      r   r,   z"Profiler.DisabledProfiler.__init__      r$   c                      y r;   r!   )r+   r   s     r   __call__z"Profiler.DisabledProfiler.__call__	  r  r$   c                      y r;   r!   r*   s    r   finishz Profiler.DisabledProfiler.finish  r  r$   Nc                      y r;   r!   r+   rv   s     r   markzProfiler.DisabledProfiler.mark  r  r$   r;   )r   rW   rX   r,   r  r	  r  r!   r$   r   DisabledProfilerr    s    				r$   r  c                    |du s|dk(  r$t        | j                        dk(  r| j                  S t        j                  d      }	 t        |j                  d         }|j                  }|dz   |j                  j                  z   }|dk(  r|| j                  vr| j                  S | xj                  dz  c_        t        t        | C  |       }|xs ||_        ||_        d|_        d	|_        t+               x|_        |_        |j1                  d
|j"                  z          |S # t        $ r% |j                  d   j                  dd      d   }Y w xY w)zEOptionally create a new profiler based on caller's qualname.
        Tenvr   r   r+   r   rC   Fz> Entering )r1   
_profilers_disabledProfilerr   rI   r   f_localsr   r   	f_globalsrf   rE   rG   _depthsuperr   __new___name_delayed
_markCount	_finishedr   
_firstTime	_lastTime_newMsg)
rV   rv   disableddelayedcaller_framecaller_object_type	qualifierfunc_qualnamer   rB   s
            r   r  zProfiler.__new__  s?    tE 1c#..6IQ6N((( }}Q'	4!%l&;&;F&C!D +33I!C,*=*=*E*EEucnn!D(((

a
Hc*3/(=	)57MCII-.
!  	M$..z:@@aHLI	Ms   D" "+EEc                     | j                   ry|t        | j                        }| xj                  dz  c_        t               }| j	                  d||| j
                  z
  dz         || _        y)zARegister or print a new message with timing information.
        Nr   z  %s: %0.4f msr.   )disabler   r  r   r  r  )r+   rv   newTimes      r   r  zProfiler.__call__-  s_     <<;doo&C1.%7T^^3t;	= r$   c                      | |       y r;   r!   r  s     r   r  zProfiler.mark:  s	    S	r$   c                     d| j                   dz
  z  |z   }| j                  r| j                  j                  ||f       y | j	                          t        ||z         y )Nr   r   )r  r  _msgsr3   r   r   )r+   rv   r   s      r   r  zProfiler._newMsg=  sK    dkkAo&,==JJsDk*JJL#*r$   c                 $    | j                          y r;   )r	  r*   s    r   __del__zProfiler.__del__E      r$   c                 >   | j                   s| j                  ryd| _         | | |       | j                  d| j                  t	               | j
                  z
  dz         t        |       xj                  dz  c_        | j                  dk  r| j                          yy)zKAdd a final message; flush the message list if no parent profiler.
        NTz"< Exiting %s, total time: %0.4f msr.   r   )	r  r&  r  r  r   r  r   r  r   r  s     r   r	  zProfiler.finishH  s~     >>T\\?I9ZZ,.4??"Bd!J	LT
Q;;?JJL r$   c           
          | j                   rLt        dj                  | j                   D cg c]  }|d   |d   z   c}             g t        |       _         y y c c}w )Nra   r   r   )r*  r   rg   r   )r+   ms     r   r   zProfiler.flushV  sI    ::$))

;1QqT!A$Y;<=!DJ ;s   A)Nr  Tr;   )r   rW   rX   rY   osenvironrL   r  rf   r  r*  r&  objectr  r  r  r  r  r  r,  r	  r   __classcell__)rB   s   @r   r   r     s    :  2D9J*4*@!!#&bJFEG6  )*8!"r$   r   c                     ddl }t        j                  | |       |j                  |      }|j	                  |       |j                  |       |S )zCommon-use for cProfiler   N)pstatscProfilerunStats
sort_statsprint_stats)coder   sortnumr6  statss         r   profiler@  \  sB    LLtLLE	T	cLr$   c                     d}| D ]r  }t        |      }t        |      }||v s|t        u r&|||<   |r|dz  dk(  rt        j                          t        j
                  |      }|rt        ||d       |dz  }t y )Nr   r.   F)firstr   )r   r   r   r   r   get_referents_getr)slistolistrB  r   eoidr   tls           r   rD  rD  l  s    	A e1g%<3#:c
af]JJLa "e5)	Qr$   c                      t        j                          t        j                         } i }t        | |       |t	        |      = |t	        |       = |t	        t        j                               = |S )zaReturn a list of all live Python objects (excluding int and long), not including the list itself.)r   r   r   rD  r   r   rI   )gclrF  s     r   get_all_objectsrL  |  sU    JJL
..
CE	#ubibgb!"Lr$   c                 $    |
t               }||    S )z,Return an object given its ID, if it exists.)rL  )rH  objectss     r   lookuprO    s    !#3<r$   c                       e Zd ZdZi Zde ee      <   d Zd Zd Zd Z	d Z
d Zed	        Zd
 Zd Zd ZddZddZd Zy)
ObjTrackera  
    Tracks all objects under the sun, reporting the changes between snapshots: what objects are created, deleted, and persistent.
    This class is very useful for tracking memory leaks. The class goes to great (but not heroic) lengths to avoid tracking 
    its own internal objects.
    
    Example:
        ot = ObjTracker()   # takes snapshot of currently existing objects
           ... do stuff ...
        ot.diff()           # prints lists of objects created and deleted since ot was initialized
           ... do stuff ...
        ot.diff()           # prints lists of objects created and deleted since last call to ot.diff()
                            # also prints list of items that were created since initialization AND have not been deleted yet
                            #   (if done correctly, this list can tell you about objects that were leaked)
           
        arrays = ot.findPersistent('ndarray')  ## returns all objects matching 'ndarray' (string match, not instance checking)
                                               ## that were considered persistent when the last diff() was run
                                               
        describeObj(arrays[0])    ## See if we can determine who has references to this array
    Nc                    i | _         i | _        i | _        i | _        i | _        d t
        j                  t        |       <   | j                  | j                   | j                  | j                  | j                  | j                  g| _	        | j                  j                  | j                         | j                  D ]  }d t
        j                  t        |      <     | j                          y r;   )	startRefs
startCountr   persistentRefsobjTypesrQ  allObjsr   r   r   r3   r?   r+   vs     r   r,   zObjTracker.__init__  s     '+
2d8$]]DNNDOOT\\SWSfSfhlhuhuv			# 	-A(,Jr!u%	- 	

r$   c                 :    | j                  | j                  |      S )zZReturn all objects matching regex that were considered 'new' when the last diff() was run.)	findTypesr   r+   r   s     r   findNewzObjTracker.findNew  s    ~~dllE22r$   c                 :    | j                  | j                  |      S )zaReturn all objects matching regex that were considered 'persistent' when the last diff() was run.)r[  rU  r\  s     r   findPersistentzObjTracker.findPersistent  s    ~~d11599r$   c                    | j                         \  }}}| j                  D ]   }| j                  | j                  |          " | j                  j                          | j                  j	                  |       |D ]  }| j                  |        | j                  j                          | j                  j	                  |       y)z
        Remember the current set of objects as the comparison for all future calls to diff()
        Called automatically on init, but can be called manually as well.
        N)r   rS  	forgetRefr   updaterememberRefrT  )r+   r   r(   r   r   s        r   r?   zObjTracker.start  s    
 !LLNeT 	.ANN4>>!,-	.d# 	 AQ	 u%r$   c           	      r   | j                         \  }}}i }t        | j                  j                               D ]:  }||vs| j                  |   ||<   | j                  |= | j	                  ||          < t        | j
                  j                               D ]:  }||vs| j
                  |   ||<   | j
                  |= | j	                  ||          < i }i }|D ]0  }	|	| j                  vs|	| j
                  vr	||	   ||	<   )||	   ||	<   2 | j
                  D ]   }
| j	                  | j
                  |
          " | j
                  j                          | j
                  j                  |       | j
                  j                  |       | j
                  D ]   }
| j                  | j
                  |
          " | j                  j                          | j                  j                  |       t        d       |j                         | j                  D ]'  }j                  |d      | j                  |   z
  |<   ) t        j                               }|j                  fd       |D ]?  }|   dk(  rd|   z  }t        d|z   ddt        |      z
  z  z   t!        |      z          A t        d	t        |      z          | j"                  ||fi | t        d
t        |      z          | j"                  ||fi | t        dt        |      z          | j"                  ||fi | y)z
        Compute all differences between the current object set and the reference set.
        Print a set of reports for created, deleted, and persistent objects
        z1----------- Count changes since start: ----------r   c                     |    S r;   r!   )ac1s    r   <lambda>z!ObjTracker.diff.<locals>.<lambda>	  s    1 r$   r   z%dr   rD   
   z5-----------  %d Deleted since last diff: ------------z5-----------  %d Created since last diff: ------------z>-----------  %d Created since start (persistent): ------------N)r   r   rS  r   ra  r   r   rb  rc  rU  r   copyrT  rL   r=  r1   r   report)r+   r   r   r(   r   delRefsr   rU  
createRefsr   r   r   typstr>  rg  s                  @r   diffzObjTracker.diff  s   
 !LLNeT dnn))+, 	+A}!^^A.
NN1%wqz*		+
 dll'')* 	+A}!\\!_
LLOwqz*		+ 
 	0A&DLL($(GJqM(,QN1%	0  	,ANN4<<?+	,N+J' 	.AT\\!_-	.
 	!!#"">2 	ABZZ\ 	6AFF1aL4??1#55BqE	6BGGI		o	& 	;A!uzA,C$*sBs3xK003q69:		; 	EGTUGT+U+EJWXJ..NQTUcQddeND2E2r$   c                 ^   | j                   j                          | j                  j                          | j                  j                          | j                  j                          t
        j                  t        |       = | j                  D ]  }t
        j                  t        |      =  y r;   )	rS  r   rT  r   rU  rQ  rW  r   r   rX  s     r   r,  zObjTracker.__del__  s{    !!#r$x( 	*A""2a5)	*r$   c                 N    t        |      | u xs t        |      | j                  v S r;   )r   r   rW  )rV   r   s     r   isObjVarzObjTracker.isObjVar"  s"    Aw#~5A#++!55r$   c                    t        d       t        j                          t               }t	        j
                         }|t        |      = |t        |j                        = t        g}i }i }|D ]  }||   }t        |      }t        |      }	t        j                  |      s||v r8	 t        j                  |      }
|
||	<   t        |      }t        |      }|| j                  |	<   d t        j                   t        |      <   |j#                  |d      dz   ||<    t        dt%        |      t%        |      fz         |||fS #  d }
Y xY w)Nz!Collecting list of all objects...r   r   z%All objects: %d   Tracked objects: %d)r   r   r   rL  r   rI   r   rE   r   r   rQ  rt  r   reftypeStrrV  rW  rL   r1   )r+   r   r6   r   r   r(   r   r   r   rH  rv  typStrs               r   r   zObjTracker.collect&  s6   12


 EOELL!"e 	/AQAq'CQ%C""1%);kk!n DIq'CQZF!'DMM#-1Jr&z*3*Q.E#J!	/$ 	5TCI8NNOUD  s   &EEc                 >    |t         j                  t        |      = y y r;   rQ  rW  r   r+   rv  s     r   ra  zObjTracker.forgetRefF  s    ?""2c7+ r$   c                 B    |d t         j                  t        |      <   y y r;   rz  r{  s     r   rc  zObjTracker.rememberRefJ  s     ?*.Jr#w' r$   c                 Z    | |       	 t        ||      }|S  |       }|S #  d }Y |S xY w)N)rN  )rO  )r+   rH  rv  r   r   s        r   rO  zObjTracker.lookupP  sF    ;#%-S$/
 
 %C
	 
s   # *c           
      6   |
t               }i i }|D ]  }| j                  |||   |      }|d| j                  |   z   }nt        |      }||vrg ||<   ||   j	                  |       j                  |ddg      }|d   dz   |d   t        |      z   g|<    t        j                               }	|	j                  fd       |	D ]K  }
d|
   d   |
   d   |
fz  }|r(|ddj                  t        t        ||
               z   z  }t        |       M y )	Nz[del] r   r   c                     |    d   S )Nr   r!   )rf  r(   s    r   rh  z#ObjTracker.report.<locals>.<lambda>m  s    a r$   ri  z
  %d	%d	%s	r   )rL  rO  rV  rw  r3   rL   r   r   r   r=  rg   mapr   r   )r+   r   allobjsshowIDsrevrH  r   r   cro  rp  r9   r(   s               @r   rl  zObjTracker.report[  s4   ?%'G 
	9C++c49g6C{s!33cl#~CHOOC 		#!u%AQ461Q4
3#78E#J
	9 EJJL!		+	, 	A!U1Xa[%(1+q$AADSXXc#c!fo666$K		r$   c                     t               }g }t        j                  |      }|D ]F  }|j                  | j                  |         s"|j                  | j                  |||   |             H |S r;   )rL  r   r   r   rV  r3   rO  )r+   r   r   rW  r   r   r   s          r   r[  zObjTracker.findTypesu  se    !#JJu 	>Axxa()DKK47G<=	> r$   r;   NF)r   rW   rX   rY   rW  r   r,   r]  r_  r?   rq  r,  classmethodrt  r   ra  rc  rO  rl  r[  r!   r$   r   rQ  rQ    so    * GGBwK 3:
&"@3F* 6 6!@,/4r$   rQ  c                 H   || g}|i }d|t        t        j                               <   d|t        |      <   t        j                          t        j
                  |       }d|t        |      <   d}|D ]  }t        |      |v rt        |      t        t        t         |            v rt        dt        |g|z         z          d}S|g|z   }t        |      |k\  rt        |      }d|vrt        |       d}t        ||||       d} |st        dt        |      z          yy)z
    Trace all reference paths backward, printing a list of different ways this object can be accessed.
    Attempts to answer the question "who has a reference to this object"
    NFzCyclic reference: Tz[_]z
Dead end: )r   r   rI   r   r   r   r   r  r   r   r1   describeObj)	r   r   r   r   r   printedrv  newPathrefStrs	            r   r  r    s#   
 |u~"&F2cmmoF2d8JJLC DF2d8G c7fc7d3r4=))&uTz)BBCG%*w<5 "7+FF"fGUGV4G  l]4001 r$   c                     t        |       }|t        t        dd      k(  rd| j                  j                  z  S t        |      S )zOCreate a more useful type string by making <instance> types report their class.InstanceTypeNz<instance of %s>)r   rM   r   rB   r   r   )r   r   s     r   rw  rw    s:    
s)C
ge^T22!CMM$:$:::3xr$   c           	         t        t        j                               di}t        j                          t        j
                  |       }d|t        |      <   |D cg c]  }t        |      |vs| }}|D ]  }t        |      t        u rZ||   } t        j                          t        j
                  |       }d|t        |      <   |D cg c]  }t        |      |vs| }}o|dk(  r#t        t        t        t        |                   |dk(  r#t        t        t        t         |                   |dk(  r"d }t        t        t        ||                   |dk(  rt        |        |dk(  r| c S |dk(  s|c S  yc c}w c c}w )	a  Pseudo-interactive function for tracing references backward.
    **Arguments:**
    
        obj:   The initial object from which to start searching
        args:  A set of string or int arguments.
               each integer selects one of obj's referrers to be the new 'obj'
               each string indicates an action to take on the current 'obj':
                  t:  print the types of obj's referrers
                  l:  print the lengths of obj's referrers (if they have __len__)
                  i:  print the IDs of obj's referrers
                  o:  print obj
                  ro: return obj
                  rr: return list of obj's referrers
    
    Examples::
    
       searchRefs(obj, 't')                    ## Print types of all objects referring to obj
       searchRefs(obj, 't', 0, 't')            ##   ..then select the first referrer and print the types of its referrers
       searchRefs(obj, 't', 0, 't', 'l')       ##   ..also print lengths of the last set of referrers
       searchRefs(obj, 0, 1, 'ro')             ## Select index 0 from obj's referrer, then select index 1 from the next set of referrers, then return that object
       
    Nrp  r   rl   c                 2    t        | d      rt        |       S y )Nr   )r   r1   )r   s    r   slenzsearchRefs.<locals>.slen  s    1i(q6Mr$   r   rorr)r   r   rI   r   r   r   r   r   r   r   r  rw  )r   r   r   r   r   rf  r  s          r   
searchRefsr    sN   . !4(FJJLC DF2d83!r!uF2A3D3 
 7c>q'CJJL##C(D#F2d8#;!r!uF':A;D;#X$s7D)*+#X$s2t}%&#X 
 $s4'(#X#J$YJ$YK7 4 <s   F.FFFc                      t        j                         } g }| ;|j                  |        |j                  | j                         | j                  } | ;|S )zoReturn list of frame objects in current stack. Useful if you want to ignore these objects in refernece searches)r   rI   r3   rE   f_back)fr   s     r   allFrameObjsr    sK    AD
-AAHH HH - Kr$   c                     t               }g }t        j                  |       }|D ]3  }||   }|j                  t	        |            s#|j                  |       5 |S )z4Return a list of objects whose typeStr matches regex)rL  r   r   r   rw  r3   )r   rW  r   r   r   r   s         r   findObjr    sX    GD


5A aj88GCL!KK Kr$   c            
         i } t         j                  j                         D ]i  \  }}t        |d      st        j
                  j                  |j                        }|d   dk(  r|dd }|| v rt        d|d|d| |          e|| |<   k y)zHList modules that have been imported more than once via different paths.__file__r  r  Nz
module at z has 2 names: z, )	r   modulesitemsr   r1  r   abspathr  r   )modsr   modmfiles       r   listRedundantModulesr    s    D[[&&( 		csJ'-9#2JED=tT%[QRDK	r$   c                     |rt        d|z  t        |       z          |i }t        t        |             }	 ||xx   dz  cc<   | j                         D ]  }t        ||||dz           |S # t        $ r d||<   Y 8w xY w)a
  
    Walk through a tree of QObjects, doing nothing to them.
    The purpose of this function is to find dead objects and generate a crash
    immediately rather than stumbling upon them later.
    Prints a count of the objects encountered, for fun. (or is it?)
    r   r   )r   rw  r   r   r   childrenwalkQObjectTree)r   countsr   r   r   childs         r   r  r    s     d5j73<'(~
d3i.Csq  9vwa89 M  ss   A+ +A<;A<c           	      z   i }t        d      D ]  }t        |t        j                        st	        |      }|t
        vryt        |      dz   |j                         z   t
        |<   	 t
        |xx   d|j                         j                         z   z  cc<   t
        |xx   d|j                         z   z  cc<   t        d|t        t
        |                |j                         t        |||         t        |j                               }|j                          |D ]  }t        ||   d|        y#  Y xY w)z7Generate a report counting all QObjects and their typesPyQtr   z	check objNr  )r  r   r   QObjectr   	QObjCacherw  
objectNameparenttextr   r   r  r   r   r=  )r   r(   r   rH  ro  rp  s         r   qObjectReportr  '  s    Ev 5c6>>*S'C)#!(!4s~~7G!G	#cNdSZZ\-D-D-F&FFNcNdSXXZ&77N +sC	#$78zz|#UG45 

DIIK !eAha !s   &AD66D:c                   .    e Zd ZdZd Zd Zd Zd Zd Zy)PrintDetectorz)Find code locations that print to stdout.c                 D    t         j                  | _        | t         _        y r;   )r   r   r*   s    r   r,   zPrintDetector.__init__A  s    jj
r$   c                 .    | j                   t        _         y r;   )r   r   r*   s    r   r   zPrintDetector.removeE  s    [[
r$   c                 $    | j                          y r;   )r   r*   s    r   r,  zPrintDetector.__del__H  r-  r$   c                 b    | j                   j                  |       t        j                          y r;   )r   writer   print_stack)r+   r   s     r   r  zPrintDetector.writeK  s     !r$   c                 8    | j                   j                          y r;   )r   r   r*   s    r   r   zPrintDetector.flushO  s    r$   N)	r   rW   rX   rY   r,   r   r,  r  r   r!   r$   r   r  r  ?  s    3! r$   r  c                     t        d      } | D cg c]  }t        |t        j                        s|! } }	 ddlm} | D ]+  }t        d|       t        d|j                  |      z         - yc c}w # t        $ r ddl}Y Ew xY w)z4Prints Thread IDs (Qt's, not OS's) for all QThreads.z	[Tt]hreadr   )sipNz--> z     Qt ID: 0x%x)	r  r   r   QThreadPyQt5r  ImportErrorr   unwrapinstance)thrrp  r  s      r   listQThreadsr  S  s    
+
C
;Z6>>:1
;C
;  :fa 3#5#5a#889: <  s   A.A.A3 3BBc                 x   d}|dz   }t        | t              rY|dz   }| j                         D ]7  \  }}||t        |      z   dz   t	        ||      j                         z   dz   z  }9 ||dz   z  }|S t        | t              st        | t              rt        |       }t        |      dk  r
|||z   z  }|S t        | t              rd}nd	}||d
   z   dz   }t        |       D ]7  \  }}||t        |      z   dz   t	        ||      j                         z   dz   z  }9 |||d   z   dz   z  }|S ||t        |       z   z  }|S )zFormat nested dict/list/tuple structures into a more human-readable string
    This function is a bit better than pprint for displaying OrderedDicts.
    rp   z    z{
z:  ra   z}
(   z[]z()r   r   )r   r   r  reprprettyre   r   r   r1   	enumerater   )	r   rh   retind2r   rY  r   dr   s	            r   r  r  `  sl    CF?D$UlJJL 	KDAq4$q'>E)F1dO,A,A,CCdJJC	Kve|  J 
D$	:dE#:Jq6B;6A:C J $%1+d"C!$ N1tc!f}u,va/D/D/FFMMN6!A$;t##C J 	vT
""Jr$   c                   ,    e Zd ZdZddZd ZddZd Zy)	ThreadTracez{ 
    Used to debug freezing by starting a new thread that reports on the 
    location of other threads periodically.
    Nc                 l    || _         t               | _        d| _        || _        | j                          y r  )intervalr
   lock_stoplogFiler?   )r+   r  r  s      r   r,   zThreadTrace.__init__  s)     G	


r$   c                 T    | j                   5  d| _        d d d        y # 1 sw Y   y xY w)NT)r  r  r*   s    r   r=   zThreadTrace.stop  s%    YY 	DJ	 	 	s   'c                     ||| _         d| _        t        j                  | j                        | _        d| j
                  _        | j
                  j                          y )NF)targetT)r  r  	threadingThreadr8  threaddaemonr?   )r+   r  s     r   r?   zThreadTrace.start  sH    $DM
&&dhh7!r$   c           	          d}t        | j                        5 }	 | j                  5  | j                  du r	 d d d        d d d        y 	 d d d        |j	                  d| d       t        j                         j                         D ]  \  }}|t        j                         j                  k(  r(t               }|j	                  d||fz         t        dj                  t        j                  |                  }|j	                  |       |j	                  d        |j	                  d       |j!                          |d	z  }t#        j$                  | j&                         M# 1 sw Y   !xY w# 1 sw Y   y xY w)
Nr   Tz
=============  THREAD FRAMES z:  ================
z<< thread %d "%s" >>
rp   ra   z1===============================================

r   )r   r  r  r  r  r   _current_framesr  r  current_threadident
threadNamer   rg   r   r   r   r{   sleepr  )r+   iter	printFiler   r6   r   r   s          r   r8  zThreadTrace.run  sI   - 	*YY zzT)	* 	* * "A$G\ ]^!$!4!4!6!<!<!> 	*IBY557=== %<DOO$>"d$KLRWWY%;%;E%BCDBOOB'OOD)	*  UV!	

4==))  	* 	*s(   E4E'E4DE4'E1	,E44E=)g      $@Nr;   )r   rW   rX   rY   r,   r=   r?   r8  r!   r$   r   r  r  }  s    *r$   r  c                 ,   | t        j                         j                  } 	 t         j                  j	                  | d      }|*	 t        j                  j                  j	                  |       }|d}|S # t
        $ r d}Y ?w xY w# t
        $ r d}Y $w xY w)a9  Return a string name for a thread id.

    If *threadId* is None, then the current thread's id is used.

    This attempts to look up thread names either from `threading._active`, or from
    QThread._names. However, note that the latter does not exist by default; rather
    you must manually add id:name pairs to a dictionary there::

        # for python threads:
        t1 = threading.Thread(name="mythread")

        # for Qt threads:
        class Thread(Qt.QThread):
            def __init__(self, name):
                self._threadname = name
                if not hasattr(Qt.QThread, '_names'):
                    Qt.QThread._names = {}
                Qt.QThread.__init__(self, *args, **kwds)
            def run(self):
                Qt.QThread._names[threading.current_thread().ident] = self._threadname
    Nz???)	r  r  r  _activerL   	Exceptionr   r  _names)threadIdr   s     r   r  r    s    , ++-33  $$Xt4 |	>>((,,X6D |K    	D	s#    A4 )B 4BBBBc                   :    e Zd ZdZi Z e       Zd Zd Zd Z	d Z
y)ThreadColorzy
    Wrapper on stdout/stderr that colors text by the current thread ID.

    *stream* must be 'stdout' or 'stderr'.
    c                 d    t        t        |      | _        |dk(  | _        t	        t        ||        y )Nstderr)rM   r   streamerrsetattr)r+   r  s     r   r,   zThreadColor.__init__  s(    c6*X%VT"r$   c                     | j                   5  t        j                  | j                  | j                         |d| j                         d d d        y # 1 sw Y   y xY w)Nr  )r  )r  r	   r  colorr  r  s     r   r  zThreadColor.write  sD    YY 	OMM$++tzz|S"TXXN	O 	O 	Os   =AAc                 z    | j                   5  | j                  j                          d d d        y # 1 sw Y   y xY wr;   )r  r  r   r*   s    r   r   zThreadColor.flush  s.    YY 	 KK	  	  	 s   1:c                     t        j                         }|| j                  vr*t        | j                        dz  dz   }|| j                  |<   | j                  |   S )N   r   )r  r  colorsr1   )r+   tidr  s      r   r  zThreadColor.color  sQ    &&(dkk!T[[!B&!+A DKK{{3r$   N)r   rW   rX   rY   r  r
   r  r,   r  r   r  r!   r$   r   r  r    s*    
 F7D#
O  r$   r  c                  p    	 ddl } | j                          | j                  d       y# t        $ r Y yw xY w)aC   Enable faulthandler for all threads. 
    
    If the faulthandler package is available, this function disables and then 
    re-enables fault handling for all threads (this is necessary to ensure any
    new threads are handled correctly), and returns True.

    If faulthandler is not available, then returns False.
    r   NT)all_threadsF)faulthandlerr&  enabler  )r  s    r   enableFaulthandlerr    s>     	- s   &) 	55r;   )   z|  r   )rp   r  |)r   )QN)r   TNNN)NFr   F)profile_run
cumulative   )T)r  NN)NFr   )F)rp   )CrY   
__future__r   
contextlibr7  r   rJ   r1  r   r   r  r{   r   r   rs   r   r   numpyr   Qtr   r   utilr	   
util.mutexr
   contextmanagerr   r   r#   r3  r&   r^   rn   r\   r}   rz   rb   r   r   r   r   r   r   r   r   r@  rD  rL  rO  rQ  r  rw  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r!   r$   r   <module>r     sh   &   	  	 	 
              $0HV 0HfG/9GRJZ63l[z$V $Rx"v x"v  
j j^ 2H7r	, 	!0F (
::/*& /*d%P &  <r$   