<commit_before># Copyright 2004, <NAME>
# Released under the terms of the MIT license
# See the file 'LICENSE.txt' in the main distribution for details.
"""

    XRCWidgets:   GUI Toolkit build around wxPython and the XRC file format

XRC is a wxWidgets standard for describing a GUI in an XML file.  This module
provides facilities to easily incorporate GUI components ('widgets') whose
layout is defined in such a file.

"""

__ver_major__ = 0
__ver_minor__ = 3
__ver_patch__  = 0
__ver_sub__ = ""
__version__ = "%d.%d.%d%s" % (__ver_major__,__ver_minor__,
                              __ver_patch__,__ver_sub__)


import sys
import os

import wx
from wx import xrc

from XRCWidgets.utils import lcurry, XMLDocTree, XMLElementData
from XRCWidgets.connectors import getConnectors


########
##
##  Module-Specific Exception Classes
##
########

class XRCWidgetsError(Exception):
    """Base class for XRCWidgets-specific Exceptions."""
    pass


########
##
##  Base XRCWidget Class
##
########


class NotGiven:
    """Sentinal to indicate that no value was given for an argument."""
    pass


class XRCWidget(object):
    """Mix-in class providing basic XRC behaviors.

    Classes inheriting from this class should also inherit from one of the
    wxPython GUI classes that can be loaded from an XRC file - for example,
    wxPanel or wxFrame.  This class provides the mechanisms for automatically
    locating the XRC file and loading the definitions from it.
    """

    # Name of the XRC file to load content from
    # Will be searched for along the default XRC file path
    # Set at class-level in the subclass to force a specific name
    _xrcfilename = None

    # Location of the XRC file to load content from
    # Can be set at class-level in the subclass to force a specific location
    _xrcfile = None

    # Name of the resource to load from the XRC file, containing definitions
    # for this object.  Defaults to the name of the class.
    # Set at class-level to specify a specific name.
    _xrcname = None

    # Whether not not to look for any connect methods with magic names of
    # the form on_<name>_<action>.  Set to false to make initialisation
    # quicker.
    _useMagicMethods = True

    def __init__(self,parent=NotGiven):
        self._xmltree = None
        if self._xrcfile is None:
            self._xrcfile = self._findXRCFile()
        pre = self._getPre()
        if parent is NotGiven:
            #  Assume the caller is doing two-phase creation themselves.
            self.PostCreate(pre)
            self.Bind(wx.EVT_WINDOW_CREATE,self.on_create)
        else:
            #  Delegate the two-phase create to the XRC loader
            self._loadXRCFile(self._xrcfile,pre,parent)

    def on_create(self,event=None):
        self.Unbind(wx.EVT_WINDOW_CREATE)
        if self._useMagicMethods:
            self._connectEventMethods()

    def compact(self):
        """Reduce memory/resource usage of the widget.

        This method is called automatically after initialisation to drop
        references to unneeded resources.  These may be accumulated as
        as time goes on, so this method may be called manually to release
        them if they are causing a problem.
        """
        self._xmltree = None

    ##  Methods for dealing with XRC resource files

    @classmethod
    def _findXRCFile(cls):
        """Locate the XRC file for this class, and return its location.

        The name of the XRC file is constructed from the name of the class
        and its defining module.  If this class is named <ClassName> and is
        defined in module <TopLevel>.<SubLevel>.<Package>, then the XRC file
        searched for will be <TopLevel>/<SubLevel>/<Package>.xrc
        The locations within the filesystem which are to be searched are
        obtained from the _getXRCFileLocations() method.
        """
        if cls._xrcfilename is None:
            filePath =  "/".join(cls.__module__.split(".")) + ".xrc"
        else:
            filePath = cls._xrcfilename
        for fileLoc in cls._getXRCFileLocations():
            pth = os.path.join(fileLoc,filePath)
            if os.path.exists(pth):
                return pth
        raise XRCWidgetsError("XRC File '%s' could not be found" % (filePath,))

    @staticmethod
    def _getXRCFileLocations():
        """Iterator over the possible locations where XRC files are kept.

        XRC files can be found in the following places:

            * the directories in sys.path
            * <sys.prefix>/share/XRCWidgets/data

        """
        for p in sys.path:
            yield p
        yield os.path.normpath(os.path.join(sys.prefix,"share/XRCWidgets/data"))

    def _loadXRCFile(self,fileNm,pre,parent):
        """Load this object's definitions from an XRC file.

        The file at <fileNm> should be an XRC file containing a resource
        with the same name as this class.  This resource's definition
        will be loaded into the current object using two-stage initialisation.
        <pre> must be the pre-initialised widget object to load into, and 
        <parent> must be the desired parent of the to-be-created widget.

        The class-level attribute _xrcname may be used to specify an alternate
        name for the resource, rather than the class name.
        """
        xrcres = xrc.XmlResource(fileNm)
        if self._xrcname is not None:
            resName = self._xrcname
        else:
            resName = self.__class__.__name__
        self._loadOn(xrcres,pre,parent,resName)
        self.PostCreate(pre)
        self.on_create()

    def _makeXmlTree(self):
        """Populate self._xmltree with a representation of the XRC file."""
        if self._xmltree is None:
            xmlfile = file(self._xrcfile)
            self._xmltree = XMLDocTree(xmlfile)

    ##  Methods for obtaining references to child widgets

    def getChild(self,cName):
        """Lookup and return a child widget by name."""
        # This can be done in two ways.  Hopefully, the child has been
        # picked up by xrc and can be obtained using XRCCTRL().
        # If not, parse the XRC file ourselves and try to find it
        chld = xrc.XRCCTRL(self,cName)
        if chld is None:
            # Find XML data on the named child, if possible
            self._makeXmlTree()
            try:
                data = self._xmltree.elements[cName]
            except:
                raise XRCWidgetsError("Child '%s' not found" % (cName,))
            # Determine object class, pass data off to appropriate method<commit_msg>use wx.CallAfter to fire the on_create event<commit_after># Copyright 2004, <NAME>
# Released under the terms of the MIT license
# See the file 'LICENSE.txt' in the main distribution for details.
"""

    XRCWidgets:   GUI Toolkit build around wxPython and the XRC file format

XRC is a wxWidgets standard for describing a GUI in an XML file.  This module
provides facilities to easily incorporate GUI components ('widgets') whose
layout is defined in such a file.

"""

__ver_major__ = 0
__ver_minor__ = 3
__ver_patch__  = 0
__ver_sub__ = ""
__version__ = "%d.%d.%d%s" % (__ver_major__,__ver_minor__,
                              __ver_patch__,__ver_sub__)


import sys
import os

import wx
from wx import xrc

from XRCWidgets.utils import lcurry, XMLDocTree, XMLElementData
from XRCWidgets.connectors import getConnectors


########
##
##  Module-Specific Exception Classes
##
########

class XRCWidgetsError(Exception):
    """Base class for XRCWidgets-specific Exceptions."""
    pass


########
##
##  Base XRCWidget Class
##
########


class NotGiven:
    """Sentinal to indicate that no value was given for an argument."""
    pass


class XRCWidget(object):
    """Mix-in class providing basic XRC behaviors.

    Classes inheriting from this class should also inherit from one of the
    wxPython GUI classes that can be loaded from an XRC file - for example,
    wxPanel or wxFrame.  This class provides the mechanisms for automatically
    locating the XRC file and loading the definitions from it.
    """

    # Name of the XRC file to load content from
    # Will be searched for along the default XRC file path
    # Set at class-level in the subclass to force a specific name
    _xrcfilename = None

    # Location of the XRC file to load content from
    # Can be set at class-level in the subclass to force a specific location
    _xrcfile = None

    # Name of the resource to load from the XRC file, containing definitions
    # for this object.  Defaults to the name of the class.
    # Set at class-level to specify a specific name.
    _xrcname = None

    # Whether not not to look for any connect methods with magic names of
    # the form on_<name>_<action>.  Set to false to make initialisation
    # quicker.
    _useMagicMethods = True

    # When this event is fired, we know the widget is fully initialized.
    _initEvent = wx.EVT_WINDOW_CREATE

    def __init__(self,parent=NotGiven):
        self._xmltree = None
        if self._xrcfile is None:
            self._xrcfile = self._findXRCFile()
        pre = self._getPre()
        if parent is NotGiven:
            #  Assume the caller is doing two-phase creation themselves.
            self.PostCreate(pre)
            self.Bind(self._initEvent,self._handle_on_create)
        else:
            #  Delegate the two-phase create to the XRC loader
            self._loadXRCFile(self._xrcfile,pre,parent)

    def _handle_on_create(self,event=None):
        self.Unbind(self._initEvent)
        wx.CallAfter(self.on_create)

    def on_create(self):
        if self._useMagicMethods:
            self._connectEventMethods()

    def compact(self):
        """Reduce memory/resource usage of the widget.

        This method is called automatically after initialisation to drop
        references to unneeded resources.  These may be accumulated as
        as time goes on, so this method may be called manually to release
        them if they are causing a problem.
        """
        self._xmltree = None

    ##  Methods for dealing with XRC resource files

    @classmethod
    def _findXRCFile(cls):
        """Locate the XRC file for this class, and return its location.

        The name of the XRC file is constructed from the name of the class
        and its defining module.  If this class is named <ClassName> and is
        defined in module <TopLevel>.<SubLevel>.<Package>, then the XRC file
        searched for will be <TopLevel>/<SubLevel>/<Package>.xrc
        The locations within the filesystem which are to be searched are
        obtained from the _getXRCFileLocations() method.
        """
        if cls._xrcfilename is None:
            filePath =  "/".join(cls.__module__.split(".")) + ".xrc"
        else:
            filePath = cls._xrcfilename
        for fileLoc in cls._getXRCFileLocations():
            pth = os.path.join(fileLoc,filePath)
            if os.path.exists(pth):
                return pth
        raise XRCWidgetsError("XRC File '%s' could not be found" % (filePath,))

    @staticmethod
    def _getXRCFileLocations():
        """Iterator over the possible locations where XRC files are kept.

        XRC files can be found in the following places:

            * the directories in sys.path
            * <sys.prefix>/share/XRCWidgets/data

        """
        for p in sys.path:
            yield p
        yield os.path.normpath(os.path.join(sys.prefix,"share/XRCWidgets/data"))

    def _loadXRCFile(self,fileNm,pre,parent):
        """Load this object's definitions from an XRC file.

        The file at <fileNm> should be an XRC file containing a resource
        with the same name as this class.  This resource's definition
        will be loaded into the current object using two-stage initialisation.
        <pre> must be the pre-initialised widget object to load into, and 
        <parent> must be the desired parent of the to-be-created widget.

        The class-level attribute _xrcname may be used to specify an alternate
        name for the resource, rather than the class name.
        """
        xrcres = xrc.XmlResource(fileNm)
        if self._xrcname is None:
            self._xrcname = self.__class__.__name__
        self._loadOn(xrcres,pre,parent,self._xrcname)
        self.PostCreate(pre)
        self.on_create()

    def _makeXmlTree(self):
        """Populate self._xmltree with a representation of the XRC file."""
        if self._xrcname is None:
            self._xrcname = self.__class__.__name__
        if self._xmltree is None:
            xmlfile = file(self._xrcfile)
            self._xmltree = XMLDocTree(xmlfile)

    ##  Methods for obtaining references to child widgets

    def getChild(self,cName):
        """Lookup and return a child widget by name."""
        # This can be done in two ways.  Hopefully, the child has been
        # picked up by xrc and can be obtained using XRCCTRL().
        # If not, parse the XRC file ourselves and try to find it
        chld = xrc.XRCCTRL(self,cName)
        if chld is None:
            # Find XML data on the named child, if possible
            self._makeXmlTree()
            try:
                data = self._xmltree.elements[cName]
            except KeyError:
                raise XRCWidgetsError("Child '%s' not found" % (cName,))
            # Determine object class, pass data off to appropriate method
{'fraction_non_alphanumeric': 0.07314711359404097, 'fraction_numerical': 0.0010428305400372439, 'mean_word_length': 2.4773374773374774, 'pattern_counts': {'":': 0, '<': 31, '<?xml version=': 0, '>': 31, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 16}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '732251', 'n_tokens_mistral': 3784, 'n_tokens_neox': 3651, 'n_words': 1469}