# -*- coding: utf-8 -*-

#-----------------------------------------------------------------------------
# Name:        HTMLCyclops.py
# Purpose:     Displays a Cyclops report in HTML format.
#              Pretty much a copy of code from Cyclops by Tim Peters
#
# Author:      of changes, Riaan Booysen
#
# Created:     2000/05/20
# RCS-ID:      $Id: HTMLCyclops.py,v 1.3 2002/03/14 06:27:49 riaan Exp $
# Copyright:   of changes (c) 1999 - 2002 Riaan Booysen
# Licence:     Dual GPL & Python
#-----------------------------------------------------------------------------

"""
Module implementing an HTML variant of Tim Peters cyclops.
"""

import Cyclops
import string
from os import path

clGreen = '#228822'
clRed = '#882222'
clBlue = '#2222FF'

def replaceLT(str):
    """
    Function to replace less than character by their HTML entity.
    
    @param str string to be changed
    @return string with lt encoded
    """
    return '<font color="#000060" size="-1"><b>'+string.replace(str, '<', '&lt;')+'</b></font>'

import repr
_repr = repr
del repr

class _CyclopsHTMLRepr(_repr.Repr):
    """
    A class to make short HTML representations of objects.
    The std repr.repr sorts dicts by keys, but we refer to
    the keys via numeric subscript in cycle reports, so first a derived
    class that leaves dicts in raw order.  Also, instances, instance
    methods and classes frequently appear in cycle reports, so avoid
    chopping their reprs at all.  We're only trying to prevent massive
    expense for massive lists, tuples & dicts.
    """
    def __init__(self):
        """
        Constructor
        """
        _repr.Repr.__init__(self)
        # Boost the limit on types we don't know about; else it's too
        # easy to get a useless repr string when adding new types via
        # CycleFinder.chase_type.
        # Perhaps better to expose this class too, but-- sheesh --
        # this module is complicated enough!
        self.maxstring = self.maxother = 40

    # override base dictionary formatter; the code is almost the same,
    # we just leave the dict order alone

    def repr_dictionary(self, x, level):
        """
        Method overriding the base dictionary formatter.
        
        @param x dictionary to be shown
        @param level level of detail
        @return string representation of the dictionary
        """
        n = len(x)
        if n == 0:
            return replaceLT('{}')
        if level <= 0:
            return replaceLT('{...}')
        s = ''
        for k, v in x.items()[:min(n, self.maxdict)]:
            if s:
                s = s + ', '
            s = s + self.repr1(k, level-1)
            s = s + ': ' + self.repr1(v, level-1)
        if n > self.maxdict:
            s = s + ', ...'
        return '{' + s + '}'

    # don't chop instance, class or instance method reprs

    def repr_instance(self, x, level):
        """
        Method overriding the base instance formatter.
        
        @param x instance object to be shown
        @param level level of detail
        @return string representation of the instance object
        """
        try:
            return replaceLT(`x`)
            # Bugs in x.__repr__() can cause arbitrary
            # exceptions -- then make up something
        except:
            return replaceLT('<' + x.__class__.__name__ + ' instance at ' + \
                   hex(id(x))[2:] + '>')

    def repr_class(self, x, level):
        """
        Method overriding the base class formatter.
        
        @param x class object to be shown
        @param level level of detail
        @return string representation of the class object
        """
        return replaceLT(`x`)

    repr_instance_method = repr_class

_quickrepr = _CyclopsHTMLRepr().repr

def find_declarer(cls, attr, found = 0):
    """
    Function to find the declarer of an attribute.
    
    @param cls class to start search from
    @param attr attribute to look for
    @param found flag indicating if already found
    @return tuple of flag indicating found status and class declaring
        the attribute
    """
    if found:
        return found, cls
    else:
        for base in cls.__bases__:
            if base.__dict__.has_key(attr):
                return 1, base
            else:
                found, basecls = find_declarer(base, attr, 0)
    return found, cls

indent = '&nbsp;&nbsp;&nbsp;&nbsp;'

class CycleFinderHTML(Cyclops.CycleFinder):
    """
    Class for finding cycles in Python data structures.

    See Cyclops module description for details.
    """
    def __init__(self):
        """
        Create a cycle finder with empty root set.
        """
        Cyclops.CycleFinder.__init__(self)
        self.report = []
        self.header = ['<h1>Cyclops report</h1>']#<h3> %s</h3><br>'%path.basename(self.model.filename)]

    def _add_section(self, name, text, docs = ''):
        """
        Method to add a section to the report.
        
        @param name anchor name
        @param text link text to be shown
        @param docs text to be shown
        """
        if docs is None:
            docs = ''
        elif docs:
            docs = docs + '<br><br>'
        self.header.append('<a href="#%s">%s</a><br>'%(name, text))
        self.report.append('<a NAME="%s"><h3>%s:</h3></a>'%(name, text))
        self.report.append(docs)

    def _print_separator(self):
        """
        Method to add a separator to the report.
        """
        self.report.append('<hr>')

    def _print_cycle(self, slice):
        """
        Method to print a cycle.
        """
        n = len(slice)
        assert n >= 2
        self.report.append('<b>%d-element cycle</b><br>' % (n-1))
        for i in xrange(n):
            obj = slice[i][0]
            self.show_obj(obj)
            if i < n-1:
                if type(obj).__name__ == 'instance method':
                    attrib = obj.im_func.func_name

                    found, attrib_decl = find_declarer(obj.im_class, attrib)
                    self.report.append('%s<font color="%s">this%s</font>-><br>' \
                      % (indent, clBlue, attrib))
                else:
                    index = slice[i+1][1]
                    attrib = self.tag_dispatcher[type(obj)](obj, index)

                    if attrib[0] == '.' and hasattr(obj, "__class__"):
                        found, attrib_decl = find_declarer(obj.__class__, attrib[1:])
                        self.report.append('%s<font color="%s">this%s</font>-><br>' \
                          % (indent, clBlue, attrib))
                    else:
                        self.report.append(indent+'this' + \
                          attrib+ '-><br>')

    def show_obj(self, obj):
        """
        obj -&gt; print short description of obj to sdtout.

        This is of the form

        <dl>
        <dt>&lt;address&gt; rc:&lt;refcount&gt; &lt;typename&gt;</dt>
            <dd>repr: &lt;shortrepr&gt;</dd>
        </dl>

        where
        <dl>
        <dt>&lt;address&gt;</dt>
            <dd>hex address of obj</dd>
        <dt>&lt;refcount&gt;</dt>
            <dd>If find_cycles() has been run and obj is in the root set
            or was found in a cycle, this is the number of references
            outstanding less the number held internally by
            CycleFinder.  In most cases, this is what the true
            refcount would be had you not used CycleFinder at all.
            You can screw that up, e.g. by installing a cycle filter
            that holds on to references to one or more cycle elements.
            If find_cycles() has not been run, or has but obj wasn't
            found in a cycle and isn't in the root set, <refcount> is
            "?".</dd>
        <dt>&lt;typename&gt;</dt>
            <dd>type(obj), as a string.  If obj.__class__ exists, also
            prints the class name.</dd>
        <dt>&lt;shortrepr&gt;</dt>
            <dd>repr(obj), but using a variant of the std module repr.py
            that limits the number of characters displayed.</dd>
        </dl>
        """
        objid = id(obj)
        rc = self.id2rc.get(objid, "?")
        self.report.append('<font size="-1" color="#700060">%s</font> rc: %d <b>%s</b>'%(hex(objid), rc, type(obj).__name__))
        if hasattr(obj, "__class__"):
            self.report.append('<font color="%s"><b>%s</b></font>'%(clBlue, str(obj.__class__)))
        self.report.append('<br>')
        self.report.append('&nbsp;&nbsp;&nbsp;&nbsp;%s<br>'%_quickrepr(obj))

    def add_stat_line(self, desc, value):
        """
        Method to add a statistics line to the report.
        
        @param desc description
        @param value value to be shown
        """
        if type(value) == type([]):
            lns = []
            for itm in value:
                lns.append('<td><b>%s</b></td>'%str(itm))
            self.report.append('<tr><td>%s</td>%s</tr>'%(desc, string.join(lns)))
        else:
            self.report.append('<tr><td>%s</td><td><b>%s</b></td></tr>' % (desc, str(value)))

    def stats_list(self):
        """
        Method to generate a list of statistics.
        
        @return statistics (list of description, value tuples)
        """
        if len(self.cycles):
            cf = '<font size="+1" color="#FF0000">%d</font>' % len(self.cycles)
        else:
            cf = '<font size="+1" color="#00FF00">%d</font>' % len(self.cycles)
        return [('Objects in root set', len(self.roots)),
                ('Distinct structured objects reachable', len(self.seenids)),
                ('Distinct structured objects in cycles', len(self.cycleobjs)),
                ('Cycles found', cf),
                ('Cycles filtered out', self.ncyclesignored),
                ('Strongly connected components', len(self.sccno2objs)),
                ('Arcs examined', self.narcs)]

    def show_stats(self, stats_list, name = 'Stats', title = 'Statistics'):
        """
        Print statistics for the last run of find_cycles.
        """
        self._print_separator()
        self._add_section(name, title)
        self.report.append('<table>')
        for desc, value in stats_list:
            self.add_stat_line(desc, value)
        self.report.append('</table>')

    def show_cycles(self):
        """
        Print all cycles to stdout.
        """
        self._print_separator()
        self._add_section('AllCycles', 'All cycles')
        n = len(self.cycles)
        self.report.append('<ul>')
        for i in xrange(n):
            self.report.append('<li>')
            self._print_cycle(self.cycles[i])
            self.report.append('</li>')
        self.report.append('</ul>')

    def show_cycleobjs(self, compare=Cyclops.typename_address_cmp):
        """
        compare=typename_address_cmp -&gt; print all objects in cycles.

        Prints to stdout.  Each distinct object find_cycles found in a
        cycle is displayed.  The set of objects found in cycles is
        first sorted by the optional "compare" function.  By default,
        objects are sorted using their type name as the primary key
        and their storage address (id) as the secondary key; among
        objects of instance type, sorts by the instances' class names;
        among objects of class type, sorts by the classes' names.
        """
        self._print_separator()
        self._add_section('CycleObjs', 'Objects involved in cycles', self.show_cycleobjs.__doc__)
        objs = self.cycleobjs.values()
        objs.sort(compare)
        for obj in objs:
            self.show_obj(obj)

    def show_sccs(self, compare=Cyclops.typename_address_cmp):
        """
        compare=typename_address_cmp -&gt; print SCCs.

        Prints to stdout.  Shows the objects in cycles partitioned into
        strongly connected components (that is, the largest groupings
        possible such that each object in an SCC is reachable from every
        other object in that SCC).  Within each SCC, objects are sorted
        as for show_cycleobjs.
        """
        self._print_separator()
        self._add_section('SCC', 'Cycle objects partitioned into maximal SCCs', self.show_sccs.__doc__)
        sccs = self.sccno2objs.values()
        n = len(sccs)
        self.report.append('<ul>')
        for i in xrange(n):
            self.report.append('<li><b>SCC %d of %d</b><br>' %(i+1, n))
            objs = sccs[i]
            objs.sort(compare)
            for obj in objs:
                self.show_obj(obj)
            self.report.append('</li>')
        self.report.append('</ul>')

    def show_arcs(self, compare=None):
        """
        compare=None -&gt; print unique arc types in cycles.

        See module docstring for details.  Briefly, each arc in a
        cycle is categorized by the type of the source node, the kind
        of arc (how we got from the source to the destination), and
        the type of the destination node.  Each line of output
        consists of those three pieces of info preceded by the count
        of arcs of that kind.  By default, the rows are sorted first
        by column 2 (source node type), then by columns 3 and 4.
        """
        self._print_separator()
        self._add_section('ArcTypes', 'Arc types involved in cycles', self.show_arcs.__doc__)
        items = self.arctypes.items()
        if compare:
            items.sort(compare)
        else:
            items.sort()
        for triple, count in items:
            self.report.append('%6d %-20s %-20s -> %-20s<br>' % ((count,) + triple))

    def show_chased_types(self):
        """
        Method to add a list of installed chasers to the report.
        """
        ct = self.get_chased_types()
        self.header.append('<h3>Installed chasers</h3>')
        self.header.append('<ul>')
        if len(ct):
            for ch in ct:
                self.header.append('<li>%s</li>'%ch.__name__)
        else:
            self.header.append('<li>None</li>')
        self.header.append('</ul>')

    def iterate_til_steady_state(self, show_objs = 0, summary = 1):
        """
        Method to purge dead root sets until a steady state is reached.
        
        @param show_objs flag indicating objects should be shown
        @param summary flag indicating a summary should be added to the report
        """
        self._print_separator()
        self._add_section('CycleCycles', 'Purge root set')
        self.header.append('<ul>')
        cc = 0
        self.report.append('Non-cyclic root set objects:')
        stats = []
        self.report.append('<ul>')
        try:
            while 1:
                sawitalready = {}
                numsurvivors = numdead = 0
                class_count = {}
                name = 'DeadRootSet%d'%cc
                desc = 'Iteration %d'%cc
                self.header.append('<a href="#%s">%s</a><br>'%(name, desc))
                self.report.append('<li><a NAME="%s"><b>%s</b></a></li><br>'%(name, desc))
                for rc, cyclic, x in self.get_rootset():
                    if not sawitalready.has_key(id(x)):
                        sawitalready[id(x)] = 1
                        if rc == 0:
                            numdead = numdead + 1
                            if show_objs:
                                self.report.append('<font color="%s">DEAD </font>'%clGreen)
                                self.show_obj(x)
                        elif not cyclic:
                            numsurvivors = numsurvivors + 1
                            if show_objs: self.show_obj(x)
                            if hasattr(x, '__class__'):
                                cn = x.__class__.__name__
                                if class_count.has_key(cn):
                                    class_count[cn][id(x)] = 0
                                else:
                                    class_count[cn] = {id(x):0}

                x = None
                desc = '<br><b><font color="%s">%d</font> dead; <font color="%s">%d</font> non-cycle & alive</b><br>' % (clGreen, numdead, clRed, numsurvivors)
                self.report.append(desc)

                desc = '<br><b>Summary of instance count:</b><br>'
                self.report.append(desc)
                clss = class_count.keys()
                clss.sort()
                for cls in clss:
                    desc = '%s: %d<br>' % (cls, len(class_count[cls]))
                    self.report.append(desc)

                sts = self.stats_list()+[('Dead', numdead), ('Non-cycle & alive', numsurvivors)]
                for idx in range(len(sts)):
                    if len(stats) < idx + 1:
                        stats.append((sts[idx][0], [sts[idx][1]]))
                    else:
                        stats[idx][1].append(sts[idx][1])

                if numdead == 0:
                    break
                self.find_cycles(1)

                cc = cc + 1

        finally:
            self.report.append('</ul>')
            self.header.append('</ul>')
            self.show_stats(stats, 'StatsFin', 'Purge root set statistics')

    def get_page(self):
        """
        Method to retrieve the report.
        
        @return report as a string
        """
        self.show_chased_types()
        return string.join(self.header, '\n')+string.join(self.report, '\n')
