def tsBestSize(self):
        '''
        '''
        borderThickness = self.tsIsBorderThickness(
            style=self.ts_Style, pixels=True)

        gaugeThickness = 1
        gaugeLength = 10
 
        if self.ts_Style & wx.GA_VERTICAL:
            # Vertical
            best = wxSize(
                (gaugeThickness * wx.pixelWidthPerCharacter + \
                 2 * borderThickness.width),
                (gaugeLength * wx.pixelHeightPerCharacter + \
                 2 * borderThickness.height))
        else:
            # Horizontal
            best = wxSize(
                (gaugeLength * wx.pixelWidthPerCharacter + \
                 2 * borderThickness.width),
                (gaugeThickness * wx.pixelHeightPerCharacter + \
                 2 * borderThickness.height))

        return (best)
    def SetItemBounds(self, item, x, y, w, h):
        """

        Modeled after TBD in sizer.cpp file of wxWidgets.
        """
        pt = wxPoint(x, y)
        sz = wxSize(item.GetMinSizeWithBorder())
        flag = int(item.GetFlag())

        if flag & wx.EXPAND or flag & wx.SHAPED:

            sz = wxSize(w, h)

        else:

            if flag & wx.ALIGN_CENTER_HORIZONTAL:

                pt.x = x + (w - sz.x) // 2

            elif flag & wx.ALIGN_RIGHT:

                pt.x = x + (w - sz.x)

            if flag & wx.ALIGN_CENTER_VERTICAL:

                pt.y = y + (h - sz.y) // 2

            elif flag & wx.ALIGN_BOTTOM:

                pt.y = y + (h - sz.y)

        item.SetDimension(pt, sz)
    def tsBestSize(self):
        """
        """
        borderThickness = self.tsIsBorderThickness(style=self.ts_Style, pixels=True)

        maxWidth = 0
        maxHeight = 0
        for choice in self.ts_Choices:
            buttonText = self.tsStripAcceleratorTextLabel(choice)
            if len(buttonText) > maxWidth:
                maxWidth = len(buttonText)
                maxHeight += 1

        if self.ts_Style & wx.RA_VERTICAL:
            # Vertical
            best = wxSize(
                (maxWidth * wx.pixelWidthPerCharacter + 2 * borderThickness.width),
                (maxHeight * wx.pixelHeightPerCharacter + 2 * borderThickness.height),
            )

        elif self.ts_Style & wx.RA_HORIZONTAL:
            # Horizontal
            best = wxSize(
                (maxWidth * wx.pixelWidthPerCharacter + 2 * borderThickness.width),
                (maxHeight * wx.pixelHeightPerCharacter + 2 * borderThickness.height),
            )

        else:
            # TBD - Should this be allowed?
            best = wxSize(
                (maxWidth * wx.pixelWidthPerCharacter + 2 * borderThickness.width),
                (maxHeight * wx.pixelHeightPerCharacter + 2 * borderThickness.height),
            )

        return best
    def tsGetBorderCharacterDimensions(self, thickness):
        """
        Return width and height of border character in pixels.

        Parameter:

        thickness --- Border line thickness in pixels.
        """
        if thickness == -1:

            if wx.USE_BORDER_BY_DEFAULT:

                # Default (1-pixel) border required.
                dimensions = wxSize(wx.pixelWidthPerCharacter, wx.pixelHeightPerCharacter)
            else:

                # No border required.
                dimensions = wxSize(0, 0)

        elif thickness == 0:

            # No border required.
            dimensions = wxSize(0, 0)

        else:

            # Override thickness and apply default (1-pixel) border.
            dimensions = wxSize(
                min(1, thickness) * wx.pixelWidthPerCharacter, min(1, thickness) * wx.pixelHeightPerCharacter
            )

        return dimensions
    def ShowFullScreen(self, show, style):
        '''
        '''
        # TBD - Under Construction.
        # Extent resize of the top level window to include its children.
        theDisplay = self.Display
 
        theDisplayPos = wxPoint(theDisplay.ClientArea.x,
                                theDisplay.ClientArea.y)

        theDisplaySize = wxSize(theDisplay.ClientArea.width,
                                theDisplay.ClientArea.height)

        self.logger.debug(
            '      ShowFullScreen (screen): pos=%s; size=%s.' % (
                str(theDisplayPos), str(theDisplaySize)))

        self.Rect = wxRect(theDisplayPos.x,
                           theDisplayPos.y,
                           theDisplaySize.width,
                           theDisplaySize.height)

        self.logger.debug(
            '      Need Event to ShowFullScreen (rect): %s.' % (
                str(self.Rect)))

        return (show)
    def tsGetClientArea(self, pixels=True):
        '''
        Returns the bounding rectangle the client area of the Frame,
        i.e., without menu bars, tool bars, status bars and such.
        '''
        parent = self.ts_Parent
        pos = wxPoint(self.ts_Rect.x, self.ts_Rect.y)
        size = wxSize(self.ts_Rect.width, self.ts_Rect.height)
        style = self.ts_Style
        name = self.ts_Name

        (myRect, myClientRect) = self.tsFrameWindowLayout(
            parent, pos, size, style, name)

        if self.ts_Rect != myRect:

            # My Area changed after by new feature
            fmt1 = 'Wrong layout. myRect (%s) ' % str(myRect)
            fmt2 = 'changed from self.ts_Rect (%s) ' % str(self.ts_Rect)
            fmt3 = 'in tsWxFrame.tsGetClientArea'
            msg = fmt1 + fmt2 + fmt3
            self.logger.wxASSERT_MSG(
                (self.ts_Rect == myRect),
                msg)

            self.ts_Rect = myRect

        if self.ts_ClientRect != myClientRect:

            # Client Area changed after by new feature
            self.ts_ClientRect = myClientRect

        return (self.ts_ClientRect)
    def SetWindow(self, window):
        """
        Set the window to be managed by this sizer item.

        Modeled after SetWindow in sizer.h file of wxWidgets.
        """
        self.logger.wxASSERT_MSG((window is not None), "SetWindow cannot have window be %s." % str(window))

        self.ts_Kind = wx.Item_Window
        self.ts_Window = window

        # window doesn't become smaller than its initial size, whatever happens
        if True:
            self.ts_MinSize = window.Size
        else:
            if window.Size is None:
                # TBD - What should size be when curses handle not yet created.
                self.ts_MinSize = wxSize(10 * wx.pixelWidthPerCharacter, 3 * wx.pixelHeightPerCharacter)
            else:
                self.ts_MinSize = window.Size

        ##        print('tsWxSizerItem.SetWindow: MinSize=%s' % self.ts_MinSize)

        if self.ts_Flag & wx.FIXED_MINSIZE:
            window.SetMinSize(self.ts_MinSize)

        # aspect ratio calculated from initial size
        self.SetRatioSize(self.ts_MinSize)
    def SetMinSizeXY(self, x, y):
        """

        Modeled after SetMinSize in sizer.h file of wxWidgets.
        """
        size = wxSize(x, y)
        if self.IsWindow():
            self.ts_Window.SetMinSize(size)
        else:
            self.ts_MinSize = size
    def CalcMin(self):
        """
        Calculate the total minimum width and height needed by all items
        in the sizer according to this sizer layout algorithm.

        This method is abstract and has to be overwritten by any derived
        class.

        Here, the sizer will do the actual calculation of its childrens
        minimal sizes.

        Implemented in wxGridBagSizer, and wxBoxSizer.
        """
        width = 0
        height = 0
        for i in range(0, self.ts_Children.GetCount()):
            node = self.ts_Children.GetIndex(i)

            item = node.GetUserData()

            size = wxSize(0, 0)
            if isinstance(self, Window):
                try:
                    parent = self.ts_Parent
                    theClientRect = parent.ClientArea
                except AttributeError:
                    parent = None
                    theClientRect = wxRect(0, 0, 0, 0)

                width = theClientRect.width
                height = theClientRect.height
                minSize = wxSize(width, height)

                self.logger.debug(
                    "CalcMin: item=%s; minSize=%s; width=%s; height=%s"
                    % (str(item), str(minSize), str(width), str(height))
                )

                size = minSize
                self.logger.debug("CalcMin: size=%s" % size)

            return size
    def GetDefaultSize(self):
        """
        Returns the default button size for this platform.
        """
        thickness = self.tsIsBorderThickness(style=self.ts_Style, pixels=False)

        if False:
            width = (len(self.ts_ButtonText) + 1) * wx.pixelWidthPerCharacter

            height = (1) * wx.pixelHeightPerCharacter
        else:
            width = (thickness.width + len(self.ts_ButtonText) + 2) * wx.pixelWidthPerCharacter

            height = (thickness.height + 2) * wx.pixelHeightPerCharacter

        return wxSize(width, height)
    def tsShow(self):
        '''
        Shows or hides the window. You may need to call Raise for a top
        level window if you want to bring it to top, although this is not
        needed if Show is called immediately after the frame creation.
        Returns True if the window has been shown or hidden or False if
        nothing was done because it already was in the requested state.
        '''
        if self.tsIsShowPermitted:

            if self.ts_Handle is None:

                myRect = wxRect(
                    self.ts_Parent.Rect.Left,
                    (self.ts_Parent.Rect.Bottom - \
                     wx.ThemeToUse['StatusBar']['WindowHeight'] - \
                     wx.pixelHeightPerCharacter),
                    self.ts_Parent.Rect.width,
                    wx.ThemeToUse['StatusBar']['WindowHeight'])

                thePosition = wxPoint(myRect.x, myRect.y)
                theSize = wxSize(myRect.width, myRect.height)

                # TBD - Update Class geometry.
                self.ts_Rect = myRect
                self.logger.debug(
                    'tsShow: myRect=%s; Rect = %s' % (myRect, self.ts_Rect))

                self.ts_BaseRect = self.ts_Rect
                if DEBUG:
                    print('tsShow: myRect=%s; Rect = %s' % (myRect, self.ts_Rect))

                self.Create(self,
                            id=-1,
                            pos=thePosition,
                            size=theSize,
                            style=self.ts_Style,
                            name=self.Name,
                            pixels=True)

            try:
                self.tsRegisterShowOrder()
            except Exception as e:
                self.logger.error('%s; %s' % (__title__, e))

            self.tsUpdate()
    def SetItemBounds(self, item, x, y, w, h ):
        '''
        '''
        pt = wxPoint(x, y)
        sz = item.GetMinSizeWithBorder()
        flag = item.GetFlag()

        if ((flag & wx.EXPAND) or \
            (flag & wx.SHAPED)):

            sz = wxSize(w, h)

        else:

            if (flag & wx.ALIGN_CENTER_HORIZONTAL):

                pt.x = x + (w - sz.width) / 2

            elif (flag & wx.ALIGN_RIGHT):

                pt.x = x + (w - sz.width)

            if (flag & wx.ALIGN_CENTER_VERTICAL):

                pt.y = y + (h - sz.height) / 2

            elif (flag & wx.ALIGN_BOTTOM):

                pt.y = y + (h - sz.height)

        msg = 'GridSizer.SetItemBounds: '  + \
              'item (%s); pt (%s); sz (%s)' % (
                  str(item),
                  str(pt),
                  str(sz))
        if DEBUG:
            print(msg)
        self.logger.debug(msg)

##        item.SetDimension(pt, sz)
        item.ts_Window.ts_Rect = wxRect(pt.x, pt.y, sz.width, sz.height)
    def CalcMin(self):
        '''
        This method is where the sizer will do the actual calculation of its
        childrens minimal sizes. You should not need to call this directly
        as it is called by Layout

        Modeled after TBD in sizer.cpp file of wxWidgets.
        '''
        width = 0
        height = 0
        for item in self.GetChildren():
            # calculate the total minimum width and height needed
            # by all items in the sizer according to this sizer's
            # layout algorithm.
            minSize = item.MinSize
            width += minSize.width
            height += minSize.height

        size = wxSize(width, height)
        self.logger.debug('CalcMin: size=%s' % size)

        return (size)
    def GetSize(self):
        """
        Get the current size of the item, as set in the last Layout.

        Modeled after GetSize in sizer.cpp file of wxWidgets.
        """
        if self.ts_Kind == wx.Item_None:
            ret = wxSize(0, 0)

        elif self.ts_Kind == wx.Item_Window:
            ret = self.ts_Window.GetSize()

        elif self.ts_Kind == wx.Item_Sizer:
            ret = self.ts_Sizer.GetSize()

        elif self.ts_Kind == wx.Item_Spacer:
            ret = self.ts_Spacer.GetSize()

        else:
            # elif self.ts_Kind == wx.Item_Max:
            self.logger.wxFAIL_MSG("Unexpected wxSizerItem.GetSize ts_Kind == wx.Item_Max.")

        border = self.tsGetBorderCharacterDimensions(thickness=self.ts_Border)

        if self.ts_Flag & wx.WEST:
            ret.x += border.width

        if self.ts_Flag & wx.EAST:
            ret.x += border.width

        if self.ts_Flag & wx.NORTH:
            ret.y += border.height

        if self.ts_Flag & wx.SOUTH:
            ret.y += border.height

        return ret
    def tsSetStdioWindowAttributes(self, title=None, pos=None, size=None, style=None, name=None):
        """
        Set the title, position, size, style and name of the output window
        if the stdio has been redirected.
        """
        if self.stdioWin:
            # TBD - Cannot set attributes when window does not exist.
            myRect = self.Display.theRedirectedStdioArea
            if title is not None:
                self.stdioWin.title = title
            else:
                self.stdioWin.title = wx.ThemeToUse["Stdio"]["Title"]

            if pos is not None:
                self.stdioWin.pos = pos
            else:
                self.stdioWin.pos = wxPoint(myRect.x, myRect.y)

            if size is not None:
                self.stdioWin.size = size
            else:
                self.stdioWin.size = wxSize(myRect.width, myRect.height)

            if style is not None:
                self.stdioWin.style = style
            elif wx.ThemeToUse["Stdio"]["Title"] == wx.StdioRedirectedTitleStr:
                self.stdioWin.style = wx.DEFAULT_STDIO_STYLE
            else:
                self.stdioWin.style = wx.DEFAULT_FRAME_STYLE

            if name is not None:
                self.stdioWin.name = name
            elif wx.ThemeToUse["Stdio"]["Title"] == wx.StdioRedirectedTitleStr:
                self.stdioWin.name = wx.StdioNameStr
            else:
                self.stdioWin.name = wx.FrameNameStr
    def tsTrapIfTooSmall(self, name, myRect):
        '''
        '''
        # TBD - Under Construction.
        if True:
            return

        minScreenDimensions = wx.ThemeToUse['MinScreenDimensions']
        minScreenWidth = minScreenDimensions['FrameWidth']
        minScreenHeight = minScreenDimensions['FrameHeight'] + \
            minScreenDimensions['MenuBarHeight'] + \
            minScreenDimensions['ToolBarHeight'] + \
            minScreenDimensions['StatusBarHeight'] + \
            minScreenDimensions['RedirectionHeight'] + \
            minScreenDimensions['TaskBarHeight']

        minClientHeight = minScreenDimensions['FrameHeight'] + \
            minScreenDimensions['MenuBarHeight'] + \
            minScreenDimensions['ToolBarHeight'] + \
            minScreenDimensions['StatusBarHeight']

        minWidth = minScreenWidth

        if name == wx.TaskBarNameStr:
            minHeight = minScreenDimensions['TaskBarHeight']

        elif name == wx.StdioNameStr:
            minHeight = minScreenDimensions['RedirectionHeight']

        else:

            minHeight = minClientHeight

        minScreenSize = wxSize(minScreenWidth // wx.pixelWidthPerCharacter,
                               minScreenHeight // wx.pixelHeightPerCharacter)

        mySize = wxSize(myRect.width // wx.pixelWidthPerCharacter,
                        myRect.height // wx.pixelHeightPerCharacter)

        minSize = wxSize(minWidth // wx.pixelWidthPerCharacter,
                         minHeight // wx.pixelHeightPerCharacter)

        actualScreen = wxObject.TheDisplay.GetGeometry(pixels=True)

        actualScreenWidth = actualScreen.width
        actualScreenHeight = actualScreen.height
        actualScreenSize = wxSize(actualScreenWidth, actualScreenHeight)

        if actualScreenSize.width < minScreenSize.width:

            fmt = '  Screen "%s" width (%d) is too small.' + \
                ' Please make screen at least (%d) columns'
            abortMsg = fmt % (wxObject.TheDisplay.Name,
                              actualScreenSize.width,
                              minScreenSize.width)

            self.logger.error('    tsTrapIfTooSmall: %s' % abortMsg)

            raise tse.UserInterfaceException(
                tse.GRAPHICAL_WINDOW_NOT_VALID, abortMsg)

        if actualScreenSize.height < minScreenSize.height:

            fmt = '  Screen "%s" height (%d) is too small.' + \
                ' Please make screen at least (%d) lines'
            abortMsg = fmt % (wxObject.TheDisplay.Name,
                              actualScreenSize.height,
                              minScreenSize.height)

            self.logger.error('    tsTrapIfTooSmall: %s' % abortMsg)

            raise tse.UserInterfaceException(
                tse.GRAPHICAL_WINDOW_NOT_VALID, abortMsg)

        if mySize.width < minSize.width:

            fmt = '  Window "%s" width (%d) is too small.' + \
                ' Please make screen at least (%d) columns'
            abortMsg = fmt % (name, mySize.width, minSize.width)

            self.logger.error('    tsTrapIfTooSmall: %s' % abortMsg)

            raise tse.UserInterfaceException(
                tse.GRAPHICAL_WINDOW_NOT_VALID, abortMsg)

        if mySize.height < minSize.height:

            fmt = '  Window "%s" height (%d) is too small.' + \
                ' Please make screen at least (%d) lines'
            abortMsg = fmt % (name, mySize.height, minSize.height)

            self.logger.error('    tsTrapIfTooSmall: %s' % abortMsg)

            raise tse.UserInterfaceException(
                tse.GRAPHICAL_WINDOW_NOT_VALID, abortMsg)
    def __init__(self, *args, **kwargs):
        """
        Constructor for Sizer, Spacer and Window variants of SizerItem.

        Design for wxPython 2.8.12 supported no arguments and no key word
        arguments. The application first had to instantiate the SizerItem
        Class and then use various Set methods to configure the kind of
        SizerItem.

        Design for wxWidgets 2.9.2.2 supported optional arguments and key
        word arguments. The application could instantiate the SizerItem
        Class in the manner of wxPython 2.8.12 or optionally instantiate
        the Sizer, Spacer or Window variant via the appropriate args and
        kwargs.

        Since there is no wxPython 2.9.2.2, the following implementation
        attempts to cover all wxWidgets 2.9.2.2 instantiation forms.
        """
        theClass = "SizerItem"

        wx.RegisterFirstCallerClassName(self, theClass)

        Object.__init__(self)

        self.tsBeginClassRegistration(theClass, wx.ID_ANY)

        # Begin setup to avoid triggering pylint errors and warnings.
        # Set Default Values

        # ***** Begin Default Attributes
        self.ts_Border = 0
        self.ts_Flag = 0
        self.ts_ID = self.ts_LastSizerItemId = wx.ID_NONE
        self.ts_Kind = wx.Item_None
        self.ts_MinSize = wxSize(0, 0)
        self.ts_MinSizeWithBorder = wxSize(0, 0)
        self.ts_Proportion = 0
        self.ts_Ratio = 0.0
        self.ts_Rect = wxRect(0, 0, 0, 0)
        self.ts_Show = False
        self.ts_Size = wxSize(0, 0)
        self.ts_Sizer = None
        self.ts_Spacer = None
        self.ts_UserData = None
        self.ts_Window = None
        # ***** End Default Attributes

        # End setup to avoid triggering pylint errors and warnings.

        if (len(args) == 0) and (len(kwargs) == 0):

            # Instatiate SizerItem Class without using args or kwargs
            # associated with Sizer, Spacer or Window variants.
            self.__init_No_Args_No_KwArgs__()

        elif (len(args) > 0) and (isinstance(args[0], wxWindow)):

            # Instatiate SizerItem Class using args or kwargs
            # associated with Window variant.

            self.__init_Item_Window__(args, kwargs)

        elif (len(args) > 0) and (isinstance(args[0], wxSizerSpacer)):

            # Instatiate SizerItem Class using args or kwargs
            # associated with Spacer variants.

            self.__init_Item_Spacer__(args, kwargs)

        else:

            # Instatiate SizerItem Class using args or kwargs
            # associated with Sizer variants.

            self.__init_Item_Sizer__(args, kwargs)

        self.tsEndClassRegistration(theClass)
    def __init__(
        self,
        parent,
        id=wx.ID_ANY,
        label=wx.EmptyString,
        pos=wx.DefaultPosition,
        size=wx.DefaultSize,
        choices=wx.PyEmptyStringArray,
        majorDimension=0,
        style=wx.RA_HORIZONTAL,
        validator=wx.DefaultValidator,
        name=wx.RadioBoxNameStr,
    ):
        """
        Create a Control. Normally you should only call this from a
        subclass __init__ as a plain old wx.Control is not very useful.
        """
        # Also, remember that wx.RA_SPECIFY_COLS means that we arrange buttons
        # in left to right order and GetMajorDim() is the number of columns
        # while wx.RA_SPECIFY_ROWS means that the buttons are arranged top to
        # bottom and GetMajorDim() is the number of rows.
        theClass = "RadioBox"

        # Capture initial caller parametsrs before they are changed
        self.caller_parent = parent
        self.caller_id = id
        self.caller_label = label
        self.caller_pos = pos
        self.caller_size = size
        self.caller_choices = choices
        self.caller_majorDimension = majorDimension
        self.caller_style = style
        self.caller_validator = validator
        self.caller_name = name

        wx.RegisterFirstCallerClassName(self, theClass)

        Control.__init__(self, parent, id=id, pos=pos, size=size, style=style, validator=validator, name=name)

        self.tsBeginClassRegistration(theClass, id)

        if DEBUG:
            self.logger.debug("               self: %s" % self)
            self.logger.debug("             parent: %s" % parent)
            self.logger.debug("                 id: %s" % self.ts_Id)
            self.logger.debug("         AssignedId: %s" % self.ts_AssignedId)
            self.logger.debug("              label: %s" % label)
            self.logger.debug("                pos: %s" % str(pos))
            self.logger.debug("               size: %s" % str(size))
            self.logger.debug("            choices: %s" % choices)
            self.logger.debug("     majorDimension: %s" % majorDimension)
            self.logger.debug("              style: 0x%X" % style)
            #            self.logger.debug('          validator: 0x%X' % validator)
            self.logger.debug("               name: %s" % name)

        self.ts_Default = False

        self.ts_Name = name
        self.ts_Parent = parent

        theTopLevelClass = self
        self.SetTopLevelAncestor(theTopLevelClass)

        if parent is None:
            self.ts_GrandParent = None
        else:
            self.ts_GrandParent = parent.Parent

        if False:
            # Leaves artifacts of different color than parent background.
            self.ts_BackgroundColour = wx.ThemeToUse["BackgroundColour"].lower()
            self.ts_ForegroundColour = wx.ThemeToUse["ForegroundColour"].lower()
        else:
            self.ts_BackgroundColour = self.Parent.ts_BackgroundColour
            self.ts_ForegroundColour = self.Parent.ts_ForegroundColour

        self.ts_Choices = choices
        self.ts_Count = len(choices)
        self.ts_Label = label
        self.ts_MajorDimension = max(majorDimension, self.ts_Count)
        self.ts_Style = style
        self.ts_Validator = validator

        myRect, myClientRect = self.tsRadioBoxLayout(parent, pos, size, style, name)
        self.ts_Rect = myRect
        self.ts_ClientRect = myClientRect

        bestSize = self.tsBestSize()
        ##        style = 0

        self.ts_ItemLabel = []
        self.ts_ItemEnabled = []
        self.ts_ItemHelpText = []
        self.ts_ItemToolTip = []
        self.ts_ItemShown = []
        self.ts_ItemWindow = []

        # TBD - Verify scaling.
        if self.ts_Style & wx.RA_HORIZONTAL:
            itemWidth = bestSize.width // (self.ts_MajorDimension + 1)
        else:
            itemWidth = bestSize.width

        for item in range(self.ts_Count):
            self.ts_ItemLabel.append(self.ts_Choices[item])
            self.ts_ItemHelpText.append(self.ts_ItemLabel[item])
            self.ts_ItemToolTip.append(self.ts_ItemLabel[item])
            self.ts_ItemShown.append(True)

            if item == 0:
                self.ts_ItemEnabled.append(True)
            else:
                self.ts_ItemEnabled.append(False)

            # TBD - Under Construction.
            if self.ts_Style & wx.RA_HORIZONTAL:
                # Horizontal layout
                posTBD = wxPoint(
                    self.Rect.x + (item * itemWidth + 2) * wx.pixelWidthPerCharacter,
                    self.Rect.y + (2) * wx.pixelHeightPerCharacter,
                )
            else:
                # Vertical layout
                posTBD = wxPoint(
                    self.Rect.x + (2) * wx.pixelWidthPerCharacter, self.Rect.y + (item + 2) * wx.pixelHeightPerCharacter
                )

            ##            sizeTBD = wxSize(
            ##                (len('(*)  ') + len(
            ##                    self.ts_ItemLabel[item])) * wx.pixelWidthPerCharacter,
            ##                wx.pixelHeightPerCharacter)

            sizeTBD = wxSize(
                (len("(*)  ") + len(self.tsStripAcceleratorTextLabel(self.ts_ItemLabel[item])))
                * wx.pixelWidthPerCharacter,
                wx.pixelHeightPerCharacter,
            )

            self.ts_ItemWindow.append(
                wxRadioButton(
                    self,
                    id=wx.ID_ANY,
                    label=self.ts_ItemLabel[item],
                    pos=posTBD,
                    size=sizeTBD,
                    style=(self.ts_Style & wx.ALIGN_LEFT | self.ts_Style & wx.ALIGN_RIGHT | wx.NO_BORDER),
                    validator=wx.DefaultValidator,
                    name=self.ts_ItemLabel[item],
                )
            )

            self.ts_ItemWindow[item].SetValue(self.ts_ItemEnabled[item])

        if self.ts_Style & wx.RA_HORIZONTAL:
            self.ts_ColumnCount = self.ts_MajorDimension
            self.ts_RowCount = 1

        elif self.ts_Style & wx.RA_VERTICAL:
            self.ts_ColumnCount = 1
            self.ts_RowCount = self.ts_MajorDimension

        else:
            # TBD - Temporary dimension
            self.ts_ColumnCount = self.ts_MajorDimension
            rows, cols = divmod(self.ts_Count, self.ts_MajorDimension)
            if cols == 0:
                self.ts_RowCount = rows
            else:
                self.ts_RowCount = rows + 1

        self.ts_Selection = 0
        self.ts_StringSelection = 0

        # Automatically Bind all mouse events ASAP (now).
        # Will register event in the SystemEventTable.
        event = EVT_COMMAND_LEFT_CLICK
        handler = self.tsOnLeftClick
        source = self
        self.Bind(event, handler, source, useSystemEventTable=True)

        # Automatically Bind all Radio Button events ASAP (now).
        # Will register event in the SystemEventTable.
        event = EVT_RADIOBUTTON
        handler = self.tsOnRadioButtonClick
        source = self
        self.Bind(event, handler, source, useSystemEventTable=True)

        self.tsEndClassRegistration(theClass)
    def __init__(self,
                 parent,
                 id=wx.ID_ANY,
                 label=wx.EmptyString,
                 pos=wx.DefaultPosition,
                 size=wx.DefaultSize,
                 style=wx.DEFAULT_PANEL_STYLE,
                 name=wx.PanelNameStr):
        '''
        Construct and show a generic Window.
        '''
        theClass = 'Panel'

        # Capture initial caller parametsrs before they are changed
        self.caller_parent = parent
        self.caller_id = id
        self.caller_label = label
        self.caller_pos = pos
        self.caller_size = size
        self.caller_style = style
        self.caller_name = name

        wx.RegisterFirstCallerClassName(self, theClass)

        if parent is None:

            # Top Level Windows (Frames & Dialogs) have no parent
            panelPos = pos
            panelSize = size

        else:

            parentClientArea = parent.ClientArea
            if pos == wx.DefaultPosition:
                panelPos = wxPoint(parentClientArea.x,
                                   parentClientArea.y)
            else:
                panelPos = pos

            if size == wx.DefaultSize:
                panelSize = wxSize(parentClientArea.width,
                                   parentClientArea.height)
            else:
                panelSize = size

        Window.__init__(self,
                        parent,
                        id=id,
                        pos=panelPos,
                        size=panelSize,
                        style=style,
                        name=name)

        self.tsBeginClassRegistration(theClass, id)

        if False:
            self.ts_Rect = wxRect(-1, -1, -1, -1)
            self.ts_ClientRect = self.ts_Rect
        else:
            (myRect, myClientRect) = self.tsPanelLayout(
                parent, panelPos, panelSize, style, name)
            self.ts_Rect = myRect
            self.ts_ClientRect = myClientRect

        thePosition = self.Position
        theSize = self.Size

        if DEBUG:
            self.logger.debug('               self: %s' % self)
            self.logger.debug('             parent: %s' % parent)
            self.logger.debug('                 id: %s' % id)
            self.logger.debug('         AssignedId: %s' % self.ts_AssignedId)
            self.logger.debug('              label: %s' % label)
            self.logger.debug('                pos: %s' % thePosition)
            self.logger.debug('               size: %s' % theSize)
            self.logger.debug('              style: 0x%X' % style)
            self.logger.debug('               name: %s' % name)

        self.ts_Label = label
        self.ts_Name = name
        self.ts_Parent = parent

        theTopLevelClass = self
        self.SetTopLevelAncestor(theTopLevelClass)

        if parent is None:
            self.ts_GrandParent = None
        else:
            self.ts_GrandParent = parent.Parent

        self.ts_BackgroundColour = wx.ThemeToUse['BackgroundColour'].lower()
        self.ts_ForegroundColour = wx.ThemeToUse['ForegroundColour'].lower()

        # Facilitate differentiation of this panel from its parent by
        # transposing the parent's foreground and background colors.
        if style == wx.BORDER_SUNKEN:

            self.ts_BackgroundColour = wx.COLOR_BLACK
            self.ts_ForegroundColour = wx.COLOR_WHITE

        elif style == wx.BORDER_RAISED:

            self.ts_BackgroundColour = wx.COLOR_WHITE
            self.ts_ForegroundColour = wx.COLOR_BLACK

        else:

            self.ts_BackgroundColour = self.ts_Parent.ts_BackgroundColour
            self.ts_ForegroundColour = self.ts_Parent.ts_ForegroundColour

        self.ts_Style = style

        # Automatically Bind all mouse events ASAP (now).
        # Will register event in the SystemEventTable.
        event = EVT_SET_FOCUS
        handler = self.SetFocusFromKbd
        source = self
        self.Bind(event,
                  handler,
                  source,
                  useSystemEventTable=True)

        self.tsEndClassRegistration(theClass)
    def CalcMin(self):
        '''
        Calculate the total minimum width and height needed by all items
        in the sizer according to this sizer layout algorithm.
        '''
        # The minimal size for the sizer should be big enough to allocate
        # its element at least its minimal size but also, and this is the
        # non-trivial part, to respect the children proportion. To satisfy
        # the latter condition we must find the greatest min-size-to-
        # proportion ratio for all elements with non-zero proportion.

        # This sizer instance only manages a single parent's client area.
        # Unlike wxWidgets, a parent's client area depends on size of
        # Top Level Window (Frame or Dialog) that depends on initial size
        # of Display Screen which was manually set by a System Operator.

        sizerClientArea = self.FindSizerClientArea()
        self.logger.debug(
            'StaticBoxSizer.CalcMin: sizerClientArea=%s' % str(
                sizerClientArea))

        self.ts_CalcMinArea = []
        self.ts_CalcMinAreaProportion = []
        self.ts_CalcMinKind = []
        self.ts_CalcMinWindow = []
        self.ts_ClientArea = []
        self.ts_ContainingWindow = None
        self.ts_MinSize = wxSize(0, 0)
        self.ts_SizeMinThis = []
        self.ts_TotalFixedSize = wxSize(0, 0)
        self.ts_TotalProportion = 0

        for i in range(0, self.ts_Children.GetCount()):
            node = self.ts_Children.GetIndex(i)

            item =  node.GetUserData()
            msg = 'StaticBoxSizer.CalcMin: item[%d]=%s' % (i, str(item))
##            print(msg)
            self.logger.debug(msg)

            if (True or item.IsShown()):

                # sizeMinThis = item.CalcMin()
                # TBD - Not sure if the following is equivalent.

                if (item.ts_Kind == wx.Item_None):

                    msg = 'Kind: %s' % 'Item_None'
                    sizeMinThis = wxSize(0, 0)
                    self.ts_CalcMinWindow += [None]

                elif (item.ts_Kind == wx.Item_Sizer):

                    msg = 'Kind: %s' % 'Item_Sizer'
                    self.ts_Sizer.Layout()
                    self.ts_CalcMinWindow += [None]
                    sizeMinThis = item.ts_Sizer.Size

                elif (item.ts_Kind == wx.Item_Spacer):

                    msg = 'Kind: %s' % 'Item_Spacer'
                    self.ts_CalcMinWindow += [None]
                    sizeMinThis = item.ts_Spacer.Size

                elif (item.ts_Kind == wx.Item_Window):

                    msg = 'Kind: %s' % 'Item_Window'
                    self.ts_CalcMinWindow += [item.ts_Window]
                    parent = item.ts_Window.ts_Parent
                    clientArea = parent.ClientArea

                    if (clientArea == sizerClientArea):

                        theRect = parent.Rect
                        theClientArea = parent.ClientArea
                        print('StaticBoxSizer.CalcMin: ' + \
                              'Rect=%s; ClientArea=%s' % (
                                  str(theRect),
                                  str(theClientArea)))

                    else:

                        theRect = parent.Rect
                        theClientArea = parent.ClientArea
                        print(
                            'StaticBoxSizer.CalcMin: ' + \
                            'Rect=%s; ClientArea=%s' % (
                                str(theRect),
                                str(theClientArea)))
                        self.logger.error(
                            'StaticBoxSizer.CalcMin: ' + \
                            'Rect=%s; ClientArea=%s' % (
                                str(theRect),
                                str(theClientArea)))

                    msg = '%s; Parent.clientArea=%s' % (msg, str(clientArea))
                    sizeMinThis = wxSize(clientArea.width, clientArea.height)

                    if (self.ts_ContainingWindow is None):

                        self.ts_ContainingWindow = parent
                        self.ts_ClientArea = clientArea

                    elif (self.ts_ContainingWindow == parent):

                        pass

                    else:

                        fmt1 = 'StaticBoxSizer.CalcMin: '
                        fmt2 = 'Rejected Parent=%s' % str(parent)
                        fmt3 = 'Previous Parent=%s' % str(
                            self.ts_ContainingWindow)
                        msgError = fmt1 + fmt2 + fmt3
                        print(msgError)
                        self.logger.error(msgError)

                elif (item.ts_Kind == wx.Item_Max):

                    msg = 'Kind: %s' % 'Item_Max'
                    self.ts_CalcMinWindow += [None]
                    sizeMinThis = wxSize(0, 0)

                else:

                    msg = 'Kind: %s' % 'Item_Unknown'
                    self.ts_CalcMinWindow += [None]
                    sizeMinThis = wxSize(0, 0)

                self.logger.debug(msg)

                propThis = item.GetProportion()

                self.ts_CalcMinArea += [sizeMinThis]
                self.ts_CalcMinAreaProportion += [propThis]
                self.ts_CalcMinKind += [item.ts_Kind]
                self.ts_SizeMinThis += [sizeMinThis]

                if (propThis != 0):

                    # Adjustable size item

                    self.ts_TotalProportion += propThis

                    msg = 'StaticBoxSizer.CalcMin: ' + \
                          'item[%d]=%s; totalProp= %s' % (
                              i, str(item), str(self.ts_TotalProportion))
                    self.logger.debug(msg)

                else:

                    # Fixed size item

                    self.ts_TotalFixedSize += sizeMinThis

                    msg = 'StaticBoxSizer.CalcMin: ' + \
                          'item[%d]=%s; totalFixed= %s' % (
                              i, str(item), str(self.ts_TotalFixedSize))
                    self.logger.debug(msg)

        for i in range(0, self.ts_Children.GetCount()):

            if (self.ts_Orientation == wx.HORIZONTAL):

                orientation = 'HORIZONTAL'
                self.ts_CalcMinArea[i].height = self.ts_ClientArea.height

                if (self.ts_CalcMinAreaProportion[i] == 0):

                    self.ts_CalcMinArea[
                        i].width = self.ts_SizeMinThis[i].width

                else:

                    scalableWidth = self.ts_ClientArea.width - \
                                    self.ts_TotalFixedSize.width

                    self.ts_CalcMinArea[i].width = int(0.5 + (
                        scalableWidth * (
                            float(self.ts_CalcMinAreaProportion[i]) /
                            float(self.ts_TotalProportion))))

            else:

                orientation = '  VERTICAL'
                self.ts_CalcMinArea[i].width = self.ts_ClientArea.width

                if (self.ts_CalcMinAreaProportion[i] == 0):

                    self.ts_CalcMinArea[
                        i].height = self.ts_SizeMinThis[i].height

                else:

                    scalableHeight = self.ts_ClientArea.height - \
                                     self.ts_TotalFixedSize.height

                    self.ts_CalcMinArea[i].height = int(0.5 + (
                        scalableHeight * (
                            float(self.ts_CalcMinAreaProportion[i]) /
                            float(self.ts_TotalProportion))))

                if True:

                    # Adjust to be multiple of standard character size
                    self.ts_CalcMinArea[i].width = (
                        (self.ts_CalcMinArea[i].width // \
                         wx.pixelWidthPerCharacter) * \
                        wx.pixelWidthPerCharacter)

                    self.ts_CalcMinArea[i].height = (
                        (self.ts_CalcMinArea[i].height // \
                         wx.pixelHeightPerCharacter) * \
                        wx.pixelHeightPerCharacter)

            fmt1 = '%s CalcMinArea[%d]: width=%3d; height=%3d; ' % (
                orientation,
                i,
                int(self.ts_CalcMinArea[i].width),
                int(self.ts_CalcMinArea[i].height))

            fmt2 = 'totalProportion=%3d' % int(self.ts_TotalProportion)

            self.logger.debug(fmt1 + fmt2)

        theCalcMinSize = self.GetSizeInMajorDir(self.ts_ClientArea)
        self.logger.debug('theCalcMinSize=%d' % theCalcMinSize)
        return (theCalcMinSize)
from tsWxGTUI_Py3x.tsLibGUI.tsWxSizerItem import SizerItem as wxSizerItem
from tsWxGTUI_Py3x.tsLibGUI.tsWxStaticBox import StaticBox

#---------------------------------------------------------------------------

##DEBUG = True
DEBUG = wx.Debug_GUI_Launch | \
        wx.Debug_GUI_Progress | \
        wx.Debug_GUI_Termination | \
        wx.Debug_GUI_Exceptions

##VERBOSE = True
VERBOSE = wx.Debug_GUI_Configuration

DEFAULT_POS = wxPoint(wx.DefaultPosition)
DEFAULT_SIZE = wxSize(wx.DefaultSize)

#---------------------------------------------------------------------------
 
class StaticBoxSizer(BoxSizer):
    '''
    Class to establish a sizer derived from wxBoxSizer but adds a static
    box around the sizer.

    The static box may be either created independently or the sizer may
    create it itself as a convenience. In any case, the sizer owns the
    wxStaticBox control and will delete it in the wxStaticBoxSizer
    destructor.

    Note that since wxWidgets 2.9.1 you are encouraged to create the
    windows which are added to wxStaticBoxSizer as children of wxStaticBox
    def tsGetRedirectedStdioArea(self, pixels=True):
        '''
        Return rectangle position and size of window used for redirected
        output from print, stdout and stderr.

        NOTE: Area includes top, bottom, left and right borders. It must
        support at least one message. Messages may optionally include a
        timestamp. The assumed length of a typical message, without its
        timestamp, but with the left and right borders, is 80 characters.
        The minimum height must therefore provide sufficient lines to
        display the full message and its timestamp.
        '''
        ###############################################################
        #      X=0         1         2         3   X=W-1
        #        01234567890123456789012345678901234
        # Y=0    +---------------------------------+ Frame Border Top
        #   1    |Client Area                      |
        #   2    |   (ex. 35 cols x 6 rows)        |
        #   3    |                                 |
        #   4    |                                 |
        #   5    +---------------------------------+ Frame Border Bottom
        #   H-9  +---------------------------------+ Stdio Border Top
        #   H-8  |Stdio Output (Optionl)           |
        #   H-7  |   (ex. 35 cols x 5 rows)        |
        #   H-6  |                                 |
        #   H-5  +---------------------------------+ Stdio Border Bottom
        #   H-4  +---------------------------------+ Task Border Top
        #   H-3  |Task Bar Output (Optional)       |
        #   H-2  |   (ex. 35 cols x 4 rows)        |
        # Y=H-1  +---------------------------------+ Task Border Bottom
        ###############################################################
        if Display.EnableRedirectArea:

            theTotalArea = self.GetGeometry(pixels=False)

            borderRows = 2
            # borderCols = 2

            if wx.ThemeToUse['Stdio']['Timestamp']:
                minLineWidth = wx.pageWidth + len('2008/07/04 05:44:52.486 -')
            else:
                minLineWidth = wx.pageWidth

            (minDisplayPixelWidth, minDisplayPixelHeight) = \
                                   wx.RedirectedWindowHeight['minDisplay']

            (minDisplayWidth, minDisplayHeight) = (
                 minDisplayPixelWidth // wx.pixelWidthPerCharacter,
                 minDisplayPixelHeight // wx.pixelHeightPerCharacter)

            minHeightPercent = int(
                wx.RedirectedWindowHeight['minHeightPercent'])

            maxHeightPercent = int(
                wx.RedirectedWindowHeight['maxHeightPercent'])

            maxRedirectedWidth = theTotalArea.width

            theTaskArea = self.tsGetTaskArea(pixels=False)

            # thePosition = wxPoint(theTotalArea.x, theTotalArea.y)
            theSize = wxSize(theTotalArea.width, theTotalArea.height)

            theRedirectedAreaOffset = - 1
            if theSize.width < minDisplayWidth:

                if theSize.height < minDisplayHeight:

                    maxRedirectedHeight = max(
                        (borderRows + int(
                            1 + minLineWidth // maxRedirectedWidth)),
                        ((theSize.height *  minHeightPercent) // 100) * \
                        int(1 + minLineWidth // maxRedirectedWidth) + \
                        theRedirectedAreaOffset)

                else:

                    maxRedirectedHeight = max(
                        (borderRows + int(
                            1 + minLineWidth // maxRedirectedWidth)),
                        ((theSize.height *  minHeightPercent) // 100) + \
                        theRedirectedAreaOffset)

            elif theSize.height < minDisplayHeight:

                maxRedirectedHeight = max(
                    (borderRows + int(
                        1 + minLineWidth // maxRedirectedWidth)),
                    ((theSize.height *  minHeightPercent) // 100) + \
                    theRedirectedAreaOffset)

            else:

                maxRedirectedHeight = max(
                    (borderRows + int(
                        1 + minLineWidth // maxRedirectedWidth)),
                    ((theSize.height *  maxHeightPercent) // 100) + \
                    theRedirectedAreaOffset)

            theRedirectedSize = wxSize(maxRedirectedWidth,
                                       maxRedirectedHeight)

            theRedirectedPos = wxPoint(
                theTaskArea.x,
                theTaskArea.y - (theRedirectedSize.height + 0))

            theCharacterArea = wxRect(theRedirectedPos.x,
                                      theRedirectedPos.y,
                                      theRedirectedSize.width,
                                      theRedirectedSize.height)

            thePixelArea = wxRect(
                theCharacterArea.x * wx.pixelWidthPerCharacter,
                theCharacterArea.y * wx.pixelHeightPerCharacter,
                theCharacterArea.width * wx.pixelWidthPerCharacter,
                theCharacterArea.height * wx.pixelHeightPerCharacter)

            if pixels:
                theArea = thePixelArea
            else:
                theArea = theCharacterArea

            if DEBUG and VERBOSE:
                self.tsPrivateLogger(
                    'tsGetRedirectedStdioArea: %s pixels = %s characters' % (
                        thePixelArea, theCharacterArea))

        else:
 
            theArea = None

            if DEBUG and VERBOSE:
                self.tsPrivateLogger(
                    'tsGetRedirectedStdioArea: %s' % theArea)
 
        return (theArea)
    def tsScrolledTextLayout(self, parent, pos, size, style, name):
        '''
        Calculate position and size of button based upon arguments.
        '''
        if (not (self.ts_Handle is None)):

            # Inhibit operation once self.ts_Handle has been
            # assigned a curses window identifier.
            return (self.ts_Rect, self.ts_ClientRect)

        thePosition = self.tsGetClassInstanceFromTuple(pos, wxPoint)
        theSize = self.tsGetClassInstanceFromTuple(size, wxSize)
        theBorder = self.tsIsBorderThickness(style, pixels=True)

        theDefaultPosition = self.tsGetClassInstanceFromTuple(
            wx.DefaultPosition, wxPoint)
 
        theDefaultSize = self.tsGetClassInstanceFromTuple(
            wx.DefaultSize, wxSize)

        label = self.ts_Text

        if theSize == theDefaultSize:
            # theDefaultSize

            theLabelSize = theSize
            self.logger.debug(
                '      theLabelSize (begin): %s' % theLabelSize)

            if label is wx.EmptyString:
                # TBD - Adjust for cursor width
                theLabelSize = wxSize(wx.pixelWidthPerCharacter,
                                      wx.pixelHeightPerCharacter)
            elif label.find('\n') == -1:
                # TBD - Remove adjustment for extra cursor width
                theLabelSize = wxSize(
                    (len(label) + len('[ ]')) * wx.pixelWidthPerCharacter,
                    wx.pixelHeightPerCharacter)
            else:
                # TBD - Remove adjustment for extra cursor width
                theLines = label.split('\n')
                maxWidth = 0
                maxHeight = len(theLines)
                for aLine in theLines:
                    if len(aLine) > maxWidth:
                        maxWidth = len(aLine)
                theLabelSize = wxSize(
                    (maxWidth + len('[ ]')) * wx.pixelWidthPerCharacter,
                    maxHeight * wx.pixelHeightPerCharacter)

            self.logger.debug(
                '      theLabelSize (end): %s' % theLabelSize)

            if thePosition == theDefaultPosition:

                # theDefaultPosition
                myRect = wxRect(parent.ClientArea.x,
                                parent.ClientArea.y,
                                theLabelSize.width,
                                theLabelSize.height)

            else:

                # Not theDefaultPosition
                myRect = wxRect(thePosition.x,
                                thePosition.y,
                                theLabelSize.width,
                                theLabelSize.height)

        else:

            # Not theDefaultSize
            if thePosition == theDefaultPosition:

                # theDefaultPosition
                myRect = wxRect(parent.ClientArea.x,
                                parent.ClientArea.y,
                                theSize.width,
                                theSize.height)

            else:

                # Not theDefaultPosition
                myRect = wxRect(thePosition.x,
                                thePosition.y,
                                theSize.width,
                                theSize.height)

        myClientRect = wxRect(myRect.x + theBorder.width,
                              myRect.y + theBorder.height,
                              myRect.width - 2 * theBorder.width,
                              myRect.height - 2 * theBorder.height)

        self.tsTrapIfTooSmall(name, myRect)
        msg = 'parent=%s; pos=%s; size=%s; name=%s; label=%s; myRect=%s' % \
              (parent, pos, size, name, label, myRect)

        self.logger.debug('    tsTextCtrlLayout: %s' % msg)

        return (myRect, myClientRect)
    def __init_Item_Spacer__(self, *args, **kwargs):
        """
        """
        # Instatiate SizerItem Class using args or kwargs
        # associated with Spacer variants.

        ##            wxSizerItem::wxSizerItem(int width,
        ##                                     int height,
        ##                                     int proportion,
        ##                                     int flag,
        ##                                     int border,
        ##                                     wxObject* userData)
        ##                       : m_kind(Item_None),
        ##                         m_sizer(NULL),
        ##                         m_minSize(width, height), // minimal size is the initial size
        ##                         m_proportion(proportion),
        ##                         m_border(border),
        ##                         m_flag(flag),
        ##                         m_id(wxID_NONE),
        ##                         m_userData(userData)
        ##            {
        ##                ASSERT_VALID_SIZER_FLAGS( m_flag );

        ##                DoSetSpacer(wxSize(width, height));
        ##            }

        # Apply arguments, key word arguments or defaults
        try:
            width = args[0]
        except IndexError:
            try:
                width = kwargs["Width"]
            except KeyError:
                width = 0

        try:
            height = args[1]
        except IndexError:
            try:
                height = kwargs["Height"]
            except KeyError:
                height = 0

        try:
            proportion = args[2]
        except IndexError:
            try:
                proportion = kwargs["Proportion"]
            except KeyError:
                proportion = 0

        try:
            flag = args[3]
        except IndexError:
            try:
                flag = kwargs["Flag"]
            except KeyError:
                flag = 0

        try:
            border = args[4]
        except IndexError:
            try:
                border = kwargs["Border"]
            except KeyError:
                border = 0

        try:
            userData = args[5]
        except IndexError:
            try:
                userData = kwargs["UserData"]
            except KeyError:
                userData = None

        self.ts_Kind = wx.Item_None
        self.ts_Sizer = None
        self.ts_Proportion = proportion
        self.ts_Border = border
        self.ts_Flag = flag
        self.ts_ID = wx.ID_NONE
        self.ts_UserData = userData

        # minimal size is the initial size
        self.ts_MinSize = wxSize(width, height)

        wxSizerFlags.ASSERT_VALID_SIZER_FLAGS(self.ts_Flag)

        self.DoSetSpacer(wxSize(width, height))
    def RecalcSizes(self):
        '''
        Using the sizes calculated by CalcMin reposition and resize all the
        items managed by this sizer. You should not need to call this
        directly as it is called by Layout.

        Modeled after RecalcSizes in sizer.cpp file of wxWidgets.
        '''
        nitems = self.CalcRowsCols()
        self.logger.debug(
            'GridSizes.RecalcSizes: nitems=%d; Rows=%d; Cols=%d' % (
            nitems, self.ts_Rows, self.ts_Cols))

        if (nitems == 0):
            return

        # find the space allotted to this sizer

        if True:

            # Use CalcMin Output and Integer Arithmetic
            pt = self.GetPosition()
            sz = self.GetSize()

            w = (sz.width - (
                (self.ts_Cols - 1) * self.ts_HGap)) / self.ts_Cols

            h = (sz.height - (
                (self.ts_Rows - 1) * self.ts_VGap)) / self.ts_Rows

        else:

            # TBD - Use CalcMin Output and Floating Point Arithmetic
            pt = self.GetPosition()
            sz = self.GetSize()

            w = (sz.width - (
                (self.ts_Cols - 1) * self.ts_HGap)) / self.ts_Cols

            h = (sz.height - (
                (self.ts_Rows - 1) * self.ts_VGap)) / self.ts_Rows

##            ptOrig = self.GetPosition()
##            xOrig = ptOrig.x
##            yOrig = ptOrig.y

##            szOrig = self.GetSize()
##            widthOrig = szOrig.width
##            heightOrig = szOrig.height

##            hGapOrig = self.ts_HGap
##            vGapOrig = self.ts_VGap
##            x = int(float(szOrig.x) + (float(wx.pixelWidthPerCharacter) / 2.0))
##            sz = wxSize(szOrig.x +
##            pt = ptOrig

##            w = (sz.width - ((self.ts_Cols - 1) * self.ts_HGap)) / self.ts_Cols

##            h = (sz.height - ((self.ts_Rows - 1) * self.ts_VGap)) / self.ts_Rows

        y = pt.y
        for r in range(self.ts_Rows):

            x = pt.x
            for c in range(self.ts_Cols):

                i = (r * self.ts_Cols) + c
                if (i < nitems):

                    node = self.ts_Children.indexedNodeList[i]

                    self.logger.wxASSERT_MSG(
                        (node is not None),
                        'GridSizer.RecalcSizes Failed to find node')

                    if True:
                        theItem = node.GetUserData()
                        thePoint = wxPoint(x, y)
                        theSize = wxSize(w, h)
                        theItem.SetDimension(thePoint, theSize)
                        theLabel = theItem.ts_Window.ts_Label
                        if DEBUG:
                            print(
                                'r=%d; c=%d; i=%d; pt=%s; sz=%s; label=%s' % (
                                    r, c, i, str(thePoint),
                                    str(theSize), theLabel))
                    self.SetItemBounds(node.GetUserData(), x, y, w, h)

                x = x + w + self.ts_HGap

            y = y + h + self.ts_VGap
    def InformFirstDirection(self, direction, size, availableOtherDir):
        """

        Modeled after InformFirstDirection in sizer.cpp file of wxWidgets.
        """

        # The size that come here will be including borders.
        # Child items should get it without borders.
        border = self.tsGetBorderCharacterDimensions(thickness=self.ts_Border)

        if size > 0:

            if direction == wx.HORIZONTAL:

                if self.ts_Flag & wx.WEST:
                    size -= border.width

                if self.ts_Flag & wx.EAST:
                    size -= border.width

            elif direction == wx.VERTICAL:

                if self.ts_Flag & wx.NORTH:
                    size -= border.height

                if self.ts_Flag & wx.SOUTH:
                    size -= border.height

        didUse = False
        # Pass the information along to the held object
        if self.IsSizer():

            didUse = self.GetSizer().InformFirstDirection(direction, size, availableOtherDir)

            if didUse:
                self.ts_MinSize = self.GetSizer().CalcMin()

        elif self.IsWindow():

            didUse = self.GetWindow().InformFirstDirection(direction, size, availableOtherDir)

            if didUse:
                self.ts_MinSize = self.ts_Window.GetEffectiveMinSize()

            # This information is useful for items with wxSHAPED flag, since
            # we can request an optimal min size for such an item. Even if
            # we overwrite the m_minSize member here, we can read it back from
            # the owned window (happens automatically).
            if (self.ts_Flag & wx.SHAPED) and (self.ts_Flag & wx.EXPAND) and direction:

                if not self.IsNullDouble(self.ts_Ratio):

                    fmt1 = "Shaped item, non-zero "
                    fmt2 = "proportion in wxSizerItem."
                    fmt3 = "InformFirstDirection()"
                    self.logger.wxCHECK_MSG((self.ts_Proportion == 0), False, (fmt1 + fmt2 + fmt3))

                    if direction == wx.HORIZONTAL and (not self.IsNullDouble(self.ts_Ratio)):

                        # Clip size so that we do not take too much
                        if (availableOtherDir >= 0) and (
                            int(size / self.ts_Ratio) - self.ts_MinSize.y
                        ) > availableOtherDir:

                            size = int((availableOtherDir + self.ts_MinSize.y) * self.ts_Ratio)

                        self.ts_MinSize = wxSize(size, int(size / self.ts_Ratio))

                    elif direction == wx.VERTICAL:

                        # Clip size so that we do not take too much
                        if (availableOtherDir >= 0) and (
                            int(size * self.ts_Ratio) - (self.ts_MinSize.x)
                        ) > availableOtherDir:

                            size = int((availableOtherDir + self.ts_MinSize.x) / self.ts_Ratio)

                        self.ts_MinSize = wxSize(int(size * self.ts_Ratio), size)

                    didUse = True

        return didUse
    def tsFrameWindowLayout(self, parent, pos, size, style, name):
        '''
        Calculate position and size of frame based upon arguments.
        '''
        if (not (self.ts_Handle is None)):

            # Inhibit operation once self.ts_Handle has been
            # assigned a curses window identifier.
            return (self.ts_Rect, self.ts_ClientRect)

        thePosition = self.tsGetClassInstanceFromTuple(pos, wxPoint)
        theSize = self.tsGetClassInstanceFromTuple(size, wxSize)
        theBorder = self.tsIsBorderThickness(style, pixels=True)

        theDefaultPosition = self.tsGetClassInstanceFromTuple(
            wx.DefaultPosition, wxPoint)

        theDefaultSize = self.tsGetClassInstanceFromTuple(
            wx.DefaultSize, wxSize)

        if name == wx.TaskBarNameStr:

            myRect = wxObject.TheDisplay.tsGetTaskArea(pixels=True)

        elif name == wx.StdioNameStr:

            myRect = wxObject.TheDisplay.tsGetRedirectedStdioArea(pixels=True)

        elif thePosition == theDefaultPosition and theSize == theDefaultSize:

            myRect = wxObject.TheDisplay.GetClientArea(pixels=True)

        elif thePosition == theDefaultPosition:

            myRect = wxRect(wxObject.TheDisplay.ClientArea.x,
                            wxObject.TheDisplay.ClientArea.y,
                            theSize.width,
                            theSize.height)

        elif theSize == theDefaultSize:

            theDisplaySize = wxSize(
                wxObject.TheDisplay.ClientArea.width,
                wxObject.TheDisplay.ClientArea.height)

            myRect = wxRect(
                thePosition.x,
                thePosition.y,
                theDisplaySize.width - thePosition.x,
                theDisplaySize.height - thePosition.y)

        else:

            myRect = wxRect(thePosition.x,
                            thePosition.y,
                            theSize.width,
                            theSize.height)

            theDisplayRect = wxObject.TheDisplay.GetClientArea()
            if not theDisplayRect.InsideRect(myRect):
                myRect = wxRect(
                    max(thePosition.x, theDisplayRect.x),
                    max(thePosition.y, theDisplayRect.y),
                    min(theSize.width, theDisplayRect.width),
                    min(theSize.height, theDisplayRect.height - 1))

            if not theDisplayRect.InsideRect(myRect):
                myRect = theDisplayRect

        try:
            if self.ts_MenuBar is None:
                offsetMenuBar = 0
            else:
                offsetMenuBar = (self.ts_MenuBar.Rect.height // \
                                 wx.pixelHeightPerCharacter) * \
                    wx.pixelHeightPerCharacter
        except AttributeError:
            offsetMenuBar = 0

        try:
            if self.ts_StatusBar is None:
                offsetStatusBar = 0
            else:
                offsetStatusBar = ((self.ts_StatusBar.Rect.height // \
                                    wx.pixelHeightPerCharacter) - 1) * \
                    wx.pixelHeightPerCharacter
        except AttributeError:
            offsetStatusBar = 0

        try:
            if self.ts_ToolBar is None:
                offsetToolBar = 0
            else:
                offsetToolBar = (self.ts_ToolBar.Rect.height // \
                                 wx.pixelHeightPerCharacter) * \
                    wx.pixelHeightPerCharacter
        except AttributeError:
            offsetToolBar = 0

        myClientRect = wxRect(myRect.x + theBorder.width,
                              myRect.y + (theBorder.height + \
                                          offsetMenuBar + \
                                          offsetToolBar),
                              myRect.width - 2 * theBorder.width,
                              myRect.height - (
                                  (2 * theBorder.height) + \
                                  offsetMenuBar + \
                                  offsetToolBar) - \
                              offsetStatusBar)

        self.tsTrapIfTooSmall(name, myRect)
        msg = 'parent=%s; pos=%s; size=%s; name=%s; title=%s; myRect=%s' % \
            (parent, pos, size, name, self.Title, myRect)

        self.logger.debug('    tsFrameWindowLayout: %s' % msg)

        return (myRect, myClientRect)
    def tsTextEntryDialogLayout(self, parent, pos, size, style, name):
        '''
        Calculate position and size of dialog based upon arguments.
        '''
        # Example Layout (wxPython TextEntryDialog)
        #
        #   Key:
        #       Caption = "Eh?"
        #       Message = "What is your favorite programming language?"
        #       Value   = "Python is the best!"
        #       Buttons = "OK" and "Cancel"
        #
        #   Layout:
        #       Title    = Caption
        #       VSizer1  = Message Line(s)
        #       VSizer2  = Value Line(s)
        #       VSizer3  = Horizontal Separator (TextLine)
        #       VSizer4  = Button(s)
        #       HSizer1  = Spacer (variable size)
        #       HSizer2  = OK Button (fixed size)
        #       HSizer3  = Cancel Button (fixed size)
        #
        # wxPython-Style (pixel-mode)
        #
        # +---------------------------------------------------------+
        # | Caption                                              [X]|
        # +---------------------------------------------------------+
        # | What is your favorite programming language?             |
        # |  +---------------------------------------------------+  |
        # |  |Python is the best!                                |  |
        # |  +---------------------------------------------------+  |
        # | ------------------------------------------------------- |
        # |                              +----------+ +----------+  |
        # |                              [    OK    ] [  Cancel  ]  |
        # |                              +----------+ +----------+  |
        # +---------------------------------------------------------+
        #
        # tsWxGTUI-Style (character-mode)
        #
        # +- Caption -------------------------------------- [?][X] -+
        # +---------------------------------------------------------+
        # | What is your favorite programming language?             |
        # |  +---------------------------------------------------+  |
        # |  |Python is the best!                                |  |
        # |  +---------------------------------------------------+  |
        # | ------------------------------------------------------- |
        # |                              [    OK    ] [  Cancel  ]  |
        # +---------------------------------------------------------+
        if (not (self.ts_Handle is None)):

            # Inhibit operation once self.ts_Handle has been
            # assigned a curses window identifier.
            return (self.ts_Rect, self.ts_ClientRect)

        thePosition = self.tsGetClassInstanceFromTuple(pos, wxPoint)
        theSize = self.tsGetClassInstanceFromTuple(size, wxSize)
        theBorder = self.tsIsBorderThickness(style, pixels=True)

        theDefaultPosition = self.tsGetClassInstanceFromTuple(
            wx.DefaultPosition, wxPoint)

        theDefaultSize = self.tsGetClassInstanceFromTuple(
            wx.DefaultSize, wxSize)

        if thePosition == theDefaultPosition and \
           theSize == theDefaultSize:

            if parent is None:

                myRect = wxRect(self.display.ClientArea.x,
                                self.display.ClientArea.y,
                                self.display.ClientArea.width,
                                self.display.ClientArea.height)
                myRect = self.display.ClientArea

            else:

                myRect = parent.GetClientArea(pixels=True)

        elif thePosition == theDefaultPosition:

            myRect = wxRect(self.display.ClientArea.x,
                            self.display.ClientArea.y,
                            theSize.width,
                            theSize.height)

        elif theSize == theDefaultSize:

            theDisplaySize = wxSize(
                self.display.ClientArea.width,
                self.display.ClientArea.height)

            myRect = wxRect(
                thePosition.x,
                thePosition.y,
                theDisplaySize.width - thePosition.x,
                theDisplaySize.height - thePosition.y)

        else:

            myRect = wxRect(thePosition.x,
                            thePosition.y,
                            theSize.width,
                            theSize.height)

            theDisplayRect = self.display.GetClientArea()
            if not theDisplayRect.InsideRect(myRect):
                myRect = wxRect(
                    max(thePosition.x, theDisplayRect.x),
                    max(thePosition.y, theDisplayRect.y),
                    min(theSize.width, theDisplayRect.width),
                    min(theSize.height, theDisplayRect.height - 1))

            if not theDisplayRect.InsideRect(myRect):
                myRect = theDisplayRect

        myClientRect = wxRect(myRect.x + theBorder.width,
                              myRect.y + theBorder.height,
                              myRect.width - 2 * theBorder.width,
                              myRect.height - 2 * theBorder.height)

        self.tsTrapIfTooSmall(name, myRect)
        msg = 'parent=%s; pos=%s; size=%s; name=%s; title=%s; myRect=%s' % \
              (parent, pos, size, name, self.Title, myRect)

        self.logger.debug('tsTextEntryDialog.' + \
                          'tsTextEntryDialogLayout: %s' % msg)

        return (myRect, myClientRect)
    def tsGaugeLayout(self, parent, pos, size, style, name):
        '''
        Calculate position and size of gauge based upon arguments.
        '''
        if (not (self.ts_Handle is None)):

            # Inhibit operation once self.ts_Handle has been
            # assigned a curses window identifier.
            return (self.ts_Rect, self.ts_ClientRect)
 
        thePosition = self.tsGetClassInstanceFromTuple(pos, wxPoint)
        theSize = self.tsGetClassInstanceFromTuple(size, wxSize)

        theDefaultPosition = self.tsGetClassInstanceFromTuple(
            wx.DefaultPosition, wxPoint)
 
        theDefaultSize = self.tsGetClassInstanceFromTuple(
            wx.DefaultSize, wxSize)

        label = self.ts_Name

        if theSize == theDefaultSize:
            # theDefaultSize

            theLabelSize = theSize
            self.logger.debug(
                '      theLabelSize (begin): %s' % theLabelSize)

            if label is wx.EmptyString:
                # TBD - Adjust for cursor width
                theLabelSize = wxSize(
                    (len(label) + len('[]')) * wx.pixelWidthPerCharacter,
                    wx.pixelHeightPerCharacter)

            elif label.find('\n') == -1:
                # TBD - Remove adjustment for extra cursor width
                theLabelSize = wxSize(
                    (len(label) + len('[ ]')) * wx.pixelWidthPerCharacter,
                    wx.pixelHeightPerCharacter)
            else:
                # TBD - Remove adjustment for extra cursor width
                theLines = label.split('\n')
                maxWidth = 0
                maxHeight = len(theLines)
                for aLine in theLines:
                    if len(aLine) > maxWidth:
                        maxWidth = len(aLine)
                theLabelSize = wxSize(
                    (maxWidth + len('[ ]')) * wx.pixelWidthPerCharacter,
                    maxHeight * wx.pixelHeightPerCharacter)

            self.logger.debug(
                '      theLabelSize (end): %s' % theLabelSize)

            if False and thePosition == theDefaultPosition:
                # theDefaultPosition

                myRect = wxRect(parent.ClientArea.x,
                                parent.ClientArea.y,
                                theLabelSize.width,
                                theLabelSize.height)

            else:
                # Not theDefaultPosition

                myRect = wxRect(thePosition.x,
                                thePosition.y,
                                theLabelSize.width,
                                theLabelSize.height)

        else:
            # Not theDefaultSize

            if False and thePosition == theDefaultPosition:
                # theDefaultPosition

                myRect = wxRect(parent.ClientArea.x,
                                parent.ClientArea.y,
                                theSize.width,
                                theSize.height)

            else:
                # Not theDefaultPosition

                myRect = wxRect(thePosition.x,
                                thePosition.y,
                                theSize.width,
                                theSize.height)

##        theDisplayRect = self.Display.GetClientArea()
##        if not theDisplayRect.InsideRect(myRect):
##            myRect = wxRect(
##                max(thePosition.x, theDisplayRect.x),
##                max(thePosition.y, theDisplayRect.y),
##                min(theSize.width, theDisplayRect.width),
##                min(theSize.height, theDisplayRect.height - 1))

##        if not theDisplayRect.InsideRect(myRect):
##            myRect = theDisplayRect

        myClientRect = wxRect(myRect.x,
                              myRect.y,
                              myRect.width,
                              myRect.height)

        self.tsTrapIfTooSmall(name, myRect)
        fmt = 'parent=%s; pos=%s; size=%s; ' + \
              'name="%s"; label="%s"; myRect=%s'
        msg = fmt % (parent, str(pos), str(size), name, label, str(myRect))

        self.logger.debug('    tsGaugeLayout: %s' % msg)

        return (myRect, myClientRect)
    def CalcMin(self):
        '''
        This method is where the sizer will do the actual calculation of its
        childrens minimal sizes. You should not need to call this directly
        as it is called by Layout

        Modeled after TBD in sizer.cpp file of wxWidgets.
        '''
        nitems = self.CalcRowsCols()
        if DEBUG:
            print(
                'GridSizes.CalcMin: nitems=%d; Rows=%d; Cols=%d' % (
                    nitems, self.ts_Rows, self.ts_Cols))

        if (nitems == 0):
            return (wxSize(0, 0))

        sizerClientArea = self.FindSizerClientArea()
        self.ts_Rect = sizerClientArea
        self.ts_Position = wxPoint(sizerClientArea.x, sizerClientArea.y)
        self.ts_Size = wxSize(sizerClientArea.width, sizerClientArea.height)
        if DEBUG:
            print(
                'GridSizer.CalcMin: sizerClientArea=%s' % str(sizerClientArea))

        sz = wxSize(
            ((sizerClientArea.width - (
                (self.ts_Cols - 1) * self.ts_HGap)) / self.ts_Cols),
            ((sizerClientArea.height - (
                (self.ts_Rows - 1) * self.ts_VGap)) / self.ts_Rows))

        if DEBUG:
            print(
                'GridSizer.CalcMin: sz=%s; sizerClientArea=%s' % (
                    str(sz),
                    str(sizerClientArea)))

        # Find the max width and height for any component
        w = 0
        h = 0
        for i in range(0, self.ts_Children.GetCount()):
            node = self.ts_Children.GetIndex(i)

            item =  node.GetUserData()
            if DEBUG:
                msg = 'GridSizer.CalcMin: item[%d]=%s' % (i, str(item))
                print(msg)

            if (item.ts_Kind == wx.Item_Sizer):
                item.ts_Sizer.Layout()

##            parent = item.ts_Window.ts_Parent
##            clientArea = parent.ClientArea

##            theRect = parent.Rect
##            theClientArea = parent.ClientArea
##            print('GridSizer.CalcMin: Rect=%s; ClientArea=%s' % (
##                str(theRect),
##                str(theClientArea)))

##            tempSize = item.CalcMin()
##            sz = tempSize
##            sz = wxSize((min(tempSize.width,
##                            ((self.ts_ContainingWindowClientArea.width /
##                              self.ts_Cols) - self.ts_Hgap))),
##                        (min(tempSize.width,
##                             ((self.ts_ContainingWindowClientArea.height /
##                               self.ts_Rows) - self.ts_Vgap))))

            w = wx.Max( w, sz.x )
            h = wx.Max( h, sz.y )

        # In case we have a nested sizer with a two step algo , give it
        # a chance to adjust to that (we give it width component)
        didChangeMinSize = False
        for i in range(0, self.ts_Children.GetCount()):
            node = self.ts_Children.GetIndex(i)

            item =  node.GetUserData()
            didChangeMinSize |= item.InformFirstDirection(
                wx.HORIZONTAL, w, -1 )

        # And redo iteration in case min size changed
        if(didChangeMinSize):

            w = h = 0
            for i in range(0, self.ts_Children.GetCount()):
                node = self.ts_Children.GetIndex(i)

                item =  node.GetUserData()
                sz = item.GetMinSizeWithBorder()

                w = wx.Max( w, sz.x )
                h = wx.Max( h, sz.y )

        return (wxSize(self.ts_Cols * w + (self.ts_Cols-1) * self.ts_HGap,
                       self.ts_Rows * h + (self.ts_Rows-1) * self.ts_VGap))