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

# Copyright (c) 2003 - 2005 Detlev Offenbach <detlev@die-offenbachs.de>
#

"""
Module implementing the handler class for reading an XML project session file.
"""

from qt import qApp

from Config import sessionFileFormatVersion
from XMLHandlerBase import XMLHandlerBase

class SessionHandler(XMLHandlerBase):
    """
    Class implementing a sax handler to read an XML project session file.
    """
    def __init__(self, project):
        """
        Constructor
        
        @param project Reference to the project object to store the
                information into.
        """
        XMLHandlerBase.__init__(self)
        
        self.startDocumentSpecific = self.startDocumentSession
        
        self.elements.update({
            'Session' : (self.startSession, self.defaultEndElement),
            'Filename' : (self.startFilename, self.endFilename),
            'ActiveWindow' : (self.startFilename, self.endFilename),
            'Breakpoint' : (self.startBreakpoint, self.endBreakpoint),
            'BpFilename' : (self.defaultStartElement, self.endBFilename),
            'Linenumber' : (self.startLinenumber, self.defaultEndElement),
            'Condition' : (self.defaultStartElement, self.endCondition),
            'Enabled' : (self.startEnabled, self.defaultEndElement),
            'Count' : (self.startCount, self.defaultEndElement),
            'Watchpoint' : (self.startWatchpoint, self.endWatchpoint),
            'Special' : (self.defaultStartElement, self.endSpecial),
            'CommandLine' : (self.defaultStartElement, self.endCommandLine),
            'WorkingDirectory' : (self.defaultStartElement, self.endWorkingDirectory),
            'Environment' : (self.defaultStartElement, self.endEnvironment),
            'ReportExceptions' : (self.startReportExceptions, self.defaultEndElement),
            'Exceptions' : (self.startExceptions, self.endExceptions),
            'Exception' : (self.defaultStartElement, self.endException),
            'TracePython' : (self.startTracePython, self.defaultEndElement),
            'CovexcPattern' : (self.defaultStartElement, self.endCovexcPattern),
            'Bookmark' : (self.startBookmark, self.endBookmark),
            'BmFilename' : (self.defaultStartElement, self.endBFilename),
        })
    
        self.project = project
        self.vm = qApp.mainWidget().getViewManager()
        self.dbg = qApp.mainWidget().getDebugger()
        self.wpViewer = qApp.mainWidget().getDebugServer().getWatchpointViewer()
        
    def startDocumentSession(self):
        """
        Handler called, when the document parsing is started.
        """
        # clear all breakpoints and bookmarks first (in case we are rereading a session file)
        files = self.project.getSources(1)
        for file in files:
            editor = self.vm.getOpenEditor(file)
            if editor is not None:
                editor.handleClearBreakpoints()
                editor.handleClearBookmarks()
        self.version = ''
        
    ###################################################
    ## below follow the individual handler functions
    ###################################################
    
    def startFilename(self, attrs):
        """
        Handler method for the "Filename" start tag.
        """
        self.buffer = ""
        self.cline = int(attrs.get("cline", "0"))
        self.cindex = int(attrs.get("cindex", "0"))
        
    def endFilename(self):
        """
        Handler method for the "Filename" end tag.
        """
        self.buffer = self.utf8_to_code(self.buffer)
        self.vm.handleOpen(self.buffer)
        ed = self.vm.getOpenEditor(self.buffer)
        if ed is not None:
            ed.setCursorPosition(self.cline, self.cindex)
            ed.ensureCursorVisible()
        
    def startBreakpoint(self, attrs):
        """
        Handler method for the "Breakpoint" start tag.
        
        @param attrs list of tag attributes
        """
        self.filename = ""
        self.lineno = 0
        self.bpCond = ""
        self.bpTemp = 0
        self.bpEnabled = 1
        self.bpCount = 0
        
    def endBreakpoint(self):
        """
        Handler method for the "Breakpoint" end tag.
        """
        self.dbg.newBreakpointWithProperties(self.filename, self.lineno,
            (self.bpCond, self.bpTemp, self.bpEnabled, self.bpCount))
            
    def startWatchpoint(self, attrs):
        """
        Handler method for the "Watchpoint" start tag.
        
        @param attrs list of tag attributes
        """
        self.bpCond = ""
        self.bpTemp = 0
        self.bpEnabled = 1
        self.bpCount = 0
        self.wpSpecialCond = ""
        
    def endWatchpoint(self):
        """
        Handler method for the "Watchpoint" end tag.
        """
        self.wpViewer.setWatchpoint((self.bpCond, self.bpTemp,
                                     self.bpEnabled, self.bpCount,
                                     self.wpSpecialCond))
        
    def endBFilename(self):
        """
        Handler method for the "BFilename" end tag.
        """
        self.filename = self.utf8_to_code(self.buffer)
        
    def startLinenumber(self, attrs):
        """
        Handler method for the "Linenumber" start tag.
        
        @param attrs list of tag attributes
        """
        self.lineno = int(attrs["value"])
        
    def endCondition(self):
        """
        Handler method for the "Condition" end tag.
        """
        cond = self.utf8_to_code(self.buffer)
        cond = self.unescape(cond)
        if cond == 'None' or cond == '':
            self.bpCond = None
        else:
            self.bpCond = cond
            
    def startEnabled(self, attrs):
        """
        Handler method for the "Enabled" start tag.
        
        @param attrs list of tag attributes
        """
        self.bpEnabled = int(attrs["value"])
        
    def startCount(self, attrs):
        """
        Handler method for the "Count" start tag.
        
        @param attrs list of tag attributes
        """
        self.bpCount = int(attrs["value"])
        
    def endSpecial(self):
        """
        Handler method for the "Special" end tag.
        """
        self.wpSpecialCond = self.utf8_to_code(self.buffer)
        
    def endCommandLine(self):
        """
        Handler method for the "CommandLine" end tag.
        """
        self.buffer = self.utf8_to_code(self.buffer)
        self.buffer = self.unescape(self.buffer)
        self.dbg.setArgvHistory(self.buffer)
        self.project.dbgCmdline = self.buffer
        
    def endWorkingDirectory(self):
        """
        Handler method for the "WorkinDirectory" end tag.
        """
        self.buffer = self.utf8_to_code(self.buffer)
        self.dbg.setWdHistory(self.buffer)
        self.project.dbgWd = self.buffer
        
    def endEnvironment(self):
        """
        Handler method for the "Environment" end tag.
        """
        self.buffer = self.utf8_to_code(self.buffer)
        self.dbg.setEnvHistory(self.buffer)
        self.project.dbgEnv = self.buffer
    
    def startReportExceptions(self, attrs):
        """
        Handler method for the "ReportExceptions" start tag.
        
        @param attrs list of tag attributes
        """
        exc = int(attrs.get("value", "0"))
        self.dbg.setExceptionReporting(exc)
        self.project.dbgReportExceptions = exc
        
    def startExceptions(self, attrs):
        """
        Handler method for the "Exceptions" start tag.
        
        @param attrs list of tag attributes
        """
        self.dbgExcList = []
        
    def endExceptions(self):
        """
        Handler method for the "Exceptions" end tag.
        """
        self.dbg.setExcList(self.dbgExcList)
        
    def endException(self):
        """
        Handler method for the "Exception" end tag.
        """
        self.buffer = self.utf8_to_code(self.buffer)
        self.dbgExcList.append(self.buffer)
        
    def startTracePython(self, attrs):
        """
        Handler method for the "TracePython" start tag.
        
        @param attrs list of tag attributes
        """
        tracePython = int(attrs.get("value", "0"))
        self.dbg.setTracePython(tracePython)
        self.project.dbgTracePython = tracePython
        
    def endCovexcPattern(self):
        """
        Handler method for the "CovexcPattern" end tag.
        """
        self.buffer = self.utf8_to_code(self.buffer)
        self.dbg.setCovexcHistory(self.buffer)
        self.project.dbgCovexcPattern = self.buffer
        
    def startBookmark(self, attrs):
        """
        Handler method for the "Bookmark" start tag.
        
        @param attrs list of tag attributes
        """
        self.filename = ""
        self.lineno = 0
        
    def endBookmark(self):
        """
        Handler method for the "Bookmark" end tag.
        """
        editor = self.vm.getOpenEditor(self.filename)
        if editor is not None:
            editor.handleBookmark(self.lineno)
        
    def startSession(self, attrs):
        """
        Handler method for the "Session" start tag.
        
        @param attrs list of tag attributes
        """
        self.version = attrs.get('version', sessionFileFormatVersion)
        
    def getVersion(self):
        """
        Public method to retrieve the version of the session.
        
        @return String containing the version number.
        """
        return self.version
